### Installation commands for LLaMA-Factory (pip or git clone) Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Shows the two recommended installation methods: pip install or cloning the GitHub repository and installing from source with pip install -e. ```bash pip install llamafactory # or git clone https://github.com/hiyouga/LLaMA-Factory.git cd LLaMA-Factory && pip install -e . ``` -------------------------------- ### Install PEFT with pip Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/peft.md Install the PEFT library using pip. ```bash pip install peft ``` -------------------------------- ### Axolotl dataset format examples (YAML) Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/axolotl.md Shows how to configure datasets in Alpaca, ShareGPT, completion, and HuggingFace formats, with example JSON structures. ```yaml # Alpaca format datasets: - path: data.jsonl type: alpaca # {"instruction": "...", "input": "...", "output": "..."} # ShareGPT format datasets: - path: data.jsonl type: sharegpt # {"conversations": [{"from": "human", "value": "..."}, {"from": "gpt", "value": "..."}]} # Completion (raw text) datasets: - path: data.jsonl type: completion # {"text": "full text here"} # HuggingFace dataset datasets: - path: tatsu-lab/alpaca type: alpaca ``` -------------------------------- ### Install Axolotl via pip or git clone Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/axolotl.md Install Axolotl using pip or clone the repository and install in editable mode. ```bash pip install axolotl # or git clone https://github.com/axolotl-ai-cloud/axolotl.git cd axolotl && pip install -e . ``` -------------------------------- ### OpenRouter config.yaml Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Example config.yaml for OpenRouter (easiest start). The API key is read from the OPENROUTER_API_KEY environment variable. ```yaml llm: mode: "openrouter" provider: "openrouter" api_key_env: "OPENROUTER_API_KEY" primary_model: "anthropic/claude-sonnet-4" ``` -------------------------------- ### Install ScholarClaw (standard) Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Standard install of ScholarClaw, sufficient for most users. ```bash pip install -e . ``` -------------------------------- ### Configure QLoRA with BitsAndBytesConfig and prepare_model_for_kbit_training Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/peft.md Set up 4-bit quantization for QLoRA. The example uses NF4 quantization with double quantization and bfloat16 compute dtype. It then prepares the model for k-bit training and applies LoRA. ```python from transformers import BitsAndBytesConfig import torch # 4-bit quantization config bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", # "nf4" or "fp4" bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, # nested quantization ) model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen2.5-3B", quantization_config=bnb_config, device_map="auto", ) # Then apply LoRA on top from peft import prepare_model_for_kbit_training model = prepare_model_for_kbit_training(model) model = get_peft_model(model, lora_config) ``` -------------------------------- ### Install TRL with pip Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Install the TRL library using pip. ```bash pip install trl ``` -------------------------------- ### Full YAML training config for LoRA fine-tuning with Qwen2.5-3B Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Complete training configuration example with model, LoRA, dataset, training, evaluation, logging, and optional QLoRA quantization settings. Set stage to sft and finetuning_type to lora. Includes common options for chat templates, cutoff length, and gradient checkpointing. ```yaml ### Model model_name_or_path: Qwen/Qwen2.5-3B trust_remote_code: true ### Method (LoRA) stage: sft # sft, pt (pretrain), rm, ppo, dpo, kto, orpo do_train: true finetuning_type: lora # lora, freeze, full lora_rank: 16 lora_alpha: 32 lora_dropout: 0.05 lora_target: all # "all" for all linear, or comma-separated names ### Dataset dataset: alpaca_en # registered dataset name or custom path template: qwen # chat template: qwen, llama3, mistral, chatglm, etc. cutoff_len: 1024 preprocessing_num_workers: 8 ### Training output_dir: ./output num_train_epochs: 3.0 per_device_train_batch_size: 4 gradient_accumulation_steps: 4 learning_rate: 2.0e-5 lr_scheduler_type: cosine warmup_ratio: 0.1 bf16: true gradient_checkpointing: true ### Evaluation val_size: 0.05 per_device_eval_batch_size: 8 eval_strategy: steps eval_steps: 500 ### Logging logging_steps: 10 save_steps: 500 save_total_limit: 3 report_to: none ### Quantization (QLoRA) quantization_bit: 4 # 4 or 8 quantization_method: bitsandbytes # bitsandbytes, gptq, awq ``` -------------------------------- ### Install ScholarClaw with browser support Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Optional install for automated browser-based paper search. Only needed if you want that feature. ```bash pip install -e ".[browser]" playwright install ``` -------------------------------- ### Configure DoRA with use_dora=True Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/peft.md Enable DoRA (Weight-Decomposed Low-Rank Adaptation) by setting use_dora=True in LoraConfig. This example targets only q_proj and v_proj. ```python lora_config = LoraConfig( r=16, lora_alpha=32, use_dora=True, # enables DoRA decomposition target_modules=["q_proj", "v_proj"], task_type=TaskType.CAUSAL_LM, ) ``` -------------------------------- ### Dataset format examples: Alpaca and ShareGPT JSON Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Two common dataset formats: Alpaca (instruction, input, output) and ShareGPT (conversations with from and value fields). Both shown as inline examples. ```json // Alpaca format {"instruction": "Translate to French", "input": "Hello", "output": "Bonjour"} // ShareGPT format {"conversations": [ {"from": "human", "value": "Hello"}, {"from": "gpt", "value": "Hi there!"} ]} ``` -------------------------------- ### Run execution bucket after manual approval Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Command to run the execution bucket after manually approving Stage 9. This starts stages 10-13. ```bash scholarclaw run -c config.yaml \ --output artifacts/YOUR-RUN-FOLDER \ --bucket execution ``` -------------------------------- ### Configure LoRA with LoraConfig and get_peft_model Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/peft.md Set up LoRA for a causal language model. The example uses rank 16, alpha 32, and targets common linear layers. It prints the number of trainable parameters. ```python from peft import LoraConfig, get_peft_model, TaskType from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B", torch_dtype=torch.bfloat16) lora_config = LoraConfig( r=16, # rank (4, 8, 16, 32, 64) lora_alpha=32, # scaling factor (typically 2*r) lora_dropout=0.05, # dropout probability target_modules=["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], task_type=TaskType.CAUSAL_LM, bias="none", # "none", "all", or "lora_only" ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() # trainable params: 13,631,488 || all params: 3,098,746,880 || trainable%: 0.44% ``` -------------------------------- ### Run Literature Collect stage with scholarclaw CLI Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-b-literature-discovery.md Command to run only the Literature Collect stage, specifying a config file and output directory. Requires browser mode installation for browser retrieval. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage LITERATURE_COLLECT ``` -------------------------------- ### SFTTrainer Dataset Format Options Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Three dataset format options for SFTTrainer: 'text' column, 'messages' column (chat format), or a formatting_func callback. The formatting_func example shows how to define a custom formatting function. ```python # Option 1: "text" column (conversational or plain text) # {"text": "### Human: question\n### Assistant: answer"} # Option 2: "messages" column (chat format, auto-applies chat template) # {"messages": [{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]} # Option 3: formatting_func callback def formatting_func(example): return f"### Question: {example['question']}\n### Answer: {example['answer']}" trainer = SFTTrainer( ..., formatting_func=formatting_func, ) ``` -------------------------------- ### Configure TrainingArguments with key parameters Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/transformers_training.md Sets up training configuration with output directory, training hyperparameters, optimizer settings, precision (bf16/fp16), logging, saving, evaluation, and other key arguments. Effective batch size is per_device_train_batch_size times gradient_accumulation_steps. gradient_checkpointing saves memory at ~20% speed cost. bf16 is preferred on Ampere+ GPUs; fp16 is for older GPUs. report_to can be 'wandb', 'tensorboard', or 'none'. ```python from transformers import TrainingArguments args = TrainingArguments( output_dir="./output", # Training num_train_epochs=3, per_device_train_batch_size=8, per_device_eval_batch_size=16, gradient_accumulation_steps=4, # effective batch = 8 * 4 = 32 gradient_checkpointing=True, # saves memory at ~20% speed cost # Optimizer learning_rate=2e-5, weight_decay=0.01, warmup_ratio=0.1, # or warmup_steps=100 lr_scheduler_type="cosine", # "linear", "cosine", "constant" optim="adamw_torch", # "adamw_torch", "adamw_8bit", "paged_adamw_8bit" # Precision bf16=True, # bfloat16 (Ampere+ GPUs) # fp16=True, # float16 (older GPUs) # Logging logging_steps=10, logging_strategy="steps", report_to="none", # "wandb", "tensorboard", "none" # Saving save_strategy="epoch", save_total_limit=2, load_best_model_at_end=True, metric_for_best_model="eval_loss", # Evaluation eval_strategy="epoch", # Other dataloader_num_workers=4, remove_unused_columns=True, seed=42, max_grad_norm=1.0, ) ``` -------------------------------- ### Run proposal bucket Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Recommended run: proposal bucket only (stages 1–9). ```bash scholarclaw run -c config.yaml --topic-file proposal.md --bucket proposal ``` -------------------------------- ### Run Stage 10 (Implementation Prep) with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-d-experiment-design.md Command to run the Implementation Prep stage, which requires an approved Stage 9. ```bash scholarclaw run -c config.yaml --output runs/my-run --bucket execution --only-stage IMPLEMENTATION_PREP ``` -------------------------------- ### Copy config template Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Create your config file by copying the provided template. ```bash cp my.config.yaml config.yaml ``` -------------------------------- ### Run Stage 01: Topic Init with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-a-research-scoping.md Command to run the TOPIC_INIT stage using a config file and a topic file. The second command runs the full proposal bucket, which includes Stage 01 and Stage 02. ```bash scholarclaw run -c config.yaml --topic-file proposal.md --only-stage TOPIC_INIT # or, for the full proposal bucket: scholarclaw run -c config.yaml --topic-file proposal.md --bucket proposal ``` -------------------------------- ### Navigate to project folder Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Navigate to the project folder in Terminal. Replace 'path/to/AutoResearchClaw' with the actual download location. ```bash cd path/to/AutoResearchClaw ``` -------------------------------- ### Open experiment plan in browser Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Command to open the experiment plan HTML file in the default browser on Mac. ```bash open artifacts/YOUR-RUN-FOLDER/stage-09/experiment_plan.html ``` -------------------------------- ### Run ScholarClaw with custom proposal file Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Command to run stages 1-9 using a custom proposal file. ```bash scholarclaw run -c config.yaml --topic-file my_proposal.md --bucket proposal ``` -------------------------------- ### Run proposal bucket with auto-approve Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Run proposal bucket with approval prompts skipped, useful for unattended runs. ```bash scholarclaw run -c config.yaml --topic-file proposal.md --bucket proposal --auto-approve ``` -------------------------------- ### Axolotl CLI commands for training, inference, and merging LoRA Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/axolotl.md Shows the CLI commands to train a model, run inference, and merge a LoRA adapter using accelerate and python -m. ```bash # Train accelerate launch -m axolotl.cli.train config.yaml # Inference accelerate launch -m axolotl.cli.inference config.yaml --lora_model_dir=./output # Merge LoRA adapter python -m axolotl.cli.merge_lora config.yaml --lora_model_dir=./output ``` -------------------------------- ### DPOTrainer - Direct Preference Optimization Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Configure and run DPOTrainer for direct preference optimization. The dataset must have columns 'prompt', 'chosen', 'rejected' or full conversations. ref_model=None uses implicit reference (PEFT). ```python from trl import DPOTrainer, DPOConfig training_args = DPOConfig( output_dir="./dpo_output", num_train_epochs=1, per_device_train_batch_size=2, gradient_accumulation_steps=8, learning_rate=5e-7, beta=0.1, # KL penalty coefficient max_length=1024, max_prompt_length=512, bf16=True, gradient_checkpointing=True, loss_type="sigmoid", # "sigmoid" (default), "hinge", "ipo" ) # Dataset must have columns: "prompt", "chosen", "rejected" # OR "chosen" and "rejected" as full conversations trainer = DPOTrainer( model=model, ref_model=None, # None = use implicit reference (PEFT) train_dataset=dpo_dataset, tokenizer=tokenizer, args=training_args, ) trainer.train() ``` -------------------------------- ### Run a bucket with scholarclaw run Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Runs a bucket using a config file and a topic file. The --output flag sets the artifacts folder; --bucket selects the bucket to run. ```bash scholarclaw run -c config.yaml --topic-file proposal.md --bucket proposal scholarclaw run -c config.yaml --output artifacts/YOUR-RUN-FOLDER --bucket execution ``` -------------------------------- ### Initialize Trainer and train, evaluate, save Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/transformers_training.md Creates a Trainer with a sequence classification model, supplies training and evaluation datasets, and demonstrates train(), evaluate(), and save_model() calls. The tokenizer and data_collator are optional; compute_metrics is optional. The model is loaded from 'bert-base-uncased' with num_labels=2. ```python from transformers import Trainer, AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained( "bert-base-uncased", num_labels=2 ) trainer = Trainer( model=model, args=args, train_dataset=train_ds, eval_dataset=eval_ds, tokenizer=tokenizer, compute_metrics=compute_metrics, # optional metric function data_collator=data_collator, # optional custom collator ) # Train train_result = trainer.train() # Evaluate metrics = trainer.evaluate() # Save trainer.save_model("./best_model") ``` -------------------------------- ### Run Stage 16: Peer Review Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-g-paper-writing.md Executes the PEER_REVIEW stage using the specified config and output directory. Produces peer_review_report.html and reviews.md in the stage-16 output folder. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage PEER_REVIEW ``` -------------------------------- ### Axolotl training configuration (YAML) Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/axolotl.md A comprehensive YAML configuration for fine-tuning a model with QLoRA, including dataset, training, precision, memory optimization, logging, and evaluation settings. ```yaml base_model: Qwen/Qwen2.5-3B model_type: AutoModelForCausalLM tokenizer_type: AutoTokenizer trust_remote_code: true # Load in 4-bit (QLoRA) load_in_4bit: true adapter: qlora # qlora, lora, or omit for full fine-tune lora_r: 16 lora_alpha: 32 lora_dropout: 0.05 lora_target_linear: true # target all linear layers # Dataset datasets: - path: my_data.jsonl type: alpaca # alpaca, sharegpt, completion, etc. # OR custom format: # type: # field_instruction: instruction # field_input: input # field_output: output # format: "{instruction}\n{input}" # Training sequence_len: 2048 sample_packing: true # pack short sequences together pad_to_sequence_len: true num_epochs: 3 micro_batch_size: 4 gradient_accumulation_steps: 4 learning_rate: 2e-5 lr_scheduler: cosine warmup_ratio: 0.1 optimizer: paged_adamw_8bit # Precision bf16: auto # auto-detect GPU capability tf32: true # Memory optimization gradient_checkpointing: true flash_attention: true # use flash attention 2 # Logging & saving logging_steps: 10 save_strategy: steps save_steps: 500 save_total_limit: 3 output_dir: ./output # Evaluation val_set_size: 0.05 eval_steps: 500 # Weights & Biases (optional) wandb_project: my-project wandb_run_id: ``` -------------------------------- ### PPOTrainer - Proximal Policy Optimization for RLHF Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Configure and run PPOTrainer for RLHF. Uses AutoModelForCausalLMWithValueHead. The training loop generates responses, computes rewards, and steps the trainer. ```python from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead config = PPOConfig( model_name="Qwen/Qwen2.5-3B", learning_rate=1.41e-5, batch_size=16, mini_batch_size=4, ppo_epochs=4, gradient_accumulation_steps=1, ) model = AutoModelForCausalLMWithValueHead.from_pretrained("Qwen/Qwen2.5-3B") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B") trainer = PPOTrainer( config=config, model=model, tokenizer=tokenizer, dataset=dataset, ) # Training loop for batch in trainer.dataloader: query_tensors = batch["input_ids"] response_tensors = trainer.generate(query_tensors, max_new_tokens=128) rewards = [reward_model(q, r) for q, r in zip(query_tensors, response_tensors)] stats = trainer.step(query_tensors, response_tensors, rewards) ``` -------------------------------- ### LM Studio config.yaml Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Alternative config.yaml for a local AI server (LM Studio) instead of OpenRouter. ```yaml llm: mode: "lmstudio" provider: "lmstudio" base_url: "http://127.0.0.1:1234/v1" primary_model: "local-model-name" ``` -------------------------------- ### List stages with scholarclaw list-stages Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Shows available stages. The optional --bucket flag filters by bucket, e.g. proposal. ```bash scholarclaw list-stages scholarclaw list-stages --bucket proposal ``` -------------------------------- ### Activate environment and set API key Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Commands to activate the virtual environment and set the OpenRouter API key before running ScholarClaw. ```bash cd path/to/AutoResearchClaw source .venv/bin/activate export OPENROUTER_API_KEY="your-key-here" ``` -------------------------------- ### Run ScholarClaw proposal and execution buckets Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Copy-paste commands for the first ScholarClaw run: the proposal bucket (stages 1–9) and then the execution bucket (stages 10–13) after approving Stage 9. Replace artifacts/ with the folder printed by the first run, e.g. artifacts/rc-20260523-153055-23e65e. ```bash # 1. Use the sample proposal, or edit proposal.md with your own research idea # 2. Proposal phase — literature, hypotheses, experiment plan scholarclaw run -c config.yaml --topic-file proposal.md --bucket proposal # 3. After you approve Stage 9 (see below), run experiments scholarclaw run -c config.yaml --output artifacts/ --bucket execution ``` -------------------------------- ### Axolotl DPO configuration (YAML) Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/axolotl.md Configuration to enable DPO training, requiring a dataset with 'chosen' and 'rejected' fields. ```yaml rl: dpo # enables DPO training # Dataset must have "chosen" and "rejected" fields datasets: - path: dpo_data.jsonl type: chat_template.default field_messages: chosen # for chosen responses # split into chosen/rejected pairs ``` -------------------------------- ### Run Stage 15: Paper Draft Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-g-paper-writing.md Executes the PAPER_DRAFT stage using the specified config and output directory. Produces paper_draft.md and claim evidence ledger files in the stage-15 output folder. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage PAPER_DRAFT ``` -------------------------------- ### Resume after crash with --resume Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Continues a run after a crash or Ctrl+C. Use --resume with the same output folder and bucket. ```bash scholarclaw run -c config.yaml --output artifacts/YOUR-RUN-FOLDER --resume --bucket proposal ``` -------------------------------- ### Create and activate Python virtual environment Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Create and activate a Python virtual environment to isolate ScholarClaw's dependencies. Run once. After activation, the Terminal prompt may show '(.venv)'. ```bash python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip ``` -------------------------------- ### Save and load LoRA adapter with save_pretrained and PeftModel Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/peft.md Save the adapter weights, load them onto a base model, and optionally merge them into the base model for deployment. ```python # Save adapter only (small file) model.save_pretrained("./lora_adapter") # Load adapter from peft import PeftModel base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B") model = PeftModel.from_pretrained(base_model, "./lora_adapter") # Merge adapter into base model (for deployment) merged_model = model.merge_and_unload() merged_model.save_pretrained("./merged_model") ``` -------------------------------- ### GRPOTrainer - Group Relative Policy Optimization Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Configure and run GRPOTrainer for group relative policy optimization. Requires a reward function that returns a list of float scores. The dataset needs a 'prompt' column. ```python from trl import GRPOTrainer, GRPOConfig training_args = GRPOConfig( output_dir="./grpo_output", num_train_epochs=1, per_device_train_batch_size=2, learning_rate=1e-6, num_generations=4, # samples per prompt for group scoring max_completion_length=256, bf16=True, ) # Requires a reward function def reward_fn(completions, prompts): # Return list of float scores return [score_completion(c) for c in completions] trainer = GRPOTrainer( model=model, reward_funcs=reward_fn, train_dataset=dataset, # needs "prompt" column tokenizer=tokenizer, args=training_args, ) trainer.train() ``` -------------------------------- ### SFTTrainer - Supervised Fine-Tuning Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Configure and run SFTTrainer for supervised fine-tuning of a causal language model. SFTConfig inherits from TrainingArguments and supports dataset formatting via dataset_text_field and packing. ```python from trl import SFTTrainer, SFTConfig from transformers import AutoModelForCausalLM, AutoTokenizer from datasets import load_dataset model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B") tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B") dataset = load_dataset("json", data_files="train.jsonl", split="train") # SFTConfig inherits from TrainingArguments training_args = SFTConfig( output_dir="./output", num_train_epochs=3, per_device_train_batch_size=4, gradient_accumulation_steps=4, learning_rate=2e-5, max_seq_length=1024, logging_steps=10, save_strategy="epoch", bf16=True, gradient_checkpointing=True, # Dataset formatting dataset_text_field="text", # column name for text packing=True, # pack short samples for efficiency ) trainer = SFTTrainer( model=model, tokenizer=tokenizer, train_dataset=dataset, args=training_args, ) trainer.train() trainer.save_model("./final_model") ``` -------------------------------- ### Run Stage 14: Paper Outline Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-g-paper-writing.md Executes the PAPER_OUTLINE stage using the specified config and output directory. Produces outline.md, publication_profile.json, and journal_profile.json in the stage-14 output folder. ```bash scholarclaw run -c config.yaml --output runs/my-run --bucket publication --only-stage PAPER_OUTLINE ``` -------------------------------- ### Run Stage 9 (Experiment Design) with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-d-experiment-design.md Commands to run the Experiment Design stage, either as a single stage or with the proposal bucket and auto-approve. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage EXPERIMENT_DESIGN scholarclaw run -c config.yaml --output runs/my-run --bucket proposal --auto-approve ``` -------------------------------- ### Tokenize dataset with AutoTokenizer Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/transformers_training.md Loads a tokenizer and maps a tokenization function over a dataset in batches. Pads to max_length=512 and truncates. The tokenized dataset is ready for Trainer. ```python from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") def tokenize_function(examples): return tokenizer( examples["text"], padding="max_length", truncation=True, max_length=512, ) tokenized_ds = dataset.map(tokenize_function, batched=True) ``` -------------------------------- ### LLaMA-Factory CLI commands for train, chat, export, and webui Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Primary CLI interface: train, chat, export, and webui commands, each using a YAML config file. The export command merges LoRA adapters. ```bash # Fine-tune with a YAML config llamafactory-cli train config.yaml # Chat with a fine-tuned model llamafactory-cli chat config.yaml # Export/merge LoRA adapter llamafactory-cli export config.yaml # Launch web UI llamafactory-cli webui ``` -------------------------------- ### Text summary with scholarclaw report Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Generates a text summary of a run. Replace YOUR-RUN-FOLDER with the actual folder name. ```bash scholarclaw report artifacts/YOUR-RUN-FOLDER ``` -------------------------------- ### Integration with PEFT/LoRA Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/trl.md Configure a LoRA adapter and pass it to any TRL trainer (e.g., SFTTrainer) via peft_config to automatically wrap the model with LoRA. ```python from peft import LoraConfig peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, target_modules=["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], task_type="CAUSAL_LM", ) # Pass peft_config to any TRL trainer trainer = SFTTrainer( model=model, peft_config=peft_config, # automatically wraps model with LoRA ..., ) ``` -------------------------------- ### DPO training YAML configuration for LoRA Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Configuration for direct preference optimization (DPO) training, requiring a dataset with chosen/rejected columns. Sets dpo_beta and dpo_loss (sigmoid, hinge, ipo). ```yaml stage: dpo do_train: true model_name_or_path: Qwen/Qwen2.5-3B finetuning_type: lora dataset: dpo_en # needs chosen/rejected columns template: qwen dpo_beta: 0.1 dpo_loss: sigmoid # sigmoid, hinge, ipo ``` -------------------------------- ### Run Knowledge Extract stage with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-b-literature-discovery.md Use this command to execute the KNOWLEDGE_EXTRACT stage with a specified configuration. It writes outputs to the runs/my-run directory and only processes the knowledge extraction stage. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage KNOWLEDGE_EXTRACT ``` -------------------------------- ### Run External Review Stage Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-i-external-review.md Commands to run the external review stage. The first runs the review bucket, the second runs only the EXTERNAL_REVIEW stage. Use --resume to resume incomplete review runs. ```bash scholarclaw run -c config.yaml --output runs/my-run --bucket review scholarclaw run -c config.yaml --output runs/my-run --only-stage EXTERNAL_REVIEW ``` -------------------------------- ### Run Stage 20 Citation Verify Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-h-finalization.md Run Stage 20 to verify bibliography entries against real APIs and flag hallucinated or weak citations. This stage is noncritical; API rate limits may require re-running later. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage CITATION_VERIFY ``` -------------------------------- ### Run folder structure Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Shows the numbered folders created by each run. HTML files are for humans; JSON/YAML files are used internally by ScholarClaw. ```text artifacts/YOUR-RUN-FOLDER/ stage-01/goal.html stage-01/proposal_search_intent.json stage-01/proposal_objectivity.json stage-01/proposal_assumption_frame.json stage-01/objectivity_contract.json stage-02/problem_tree.html ... stage-09/experiment_plan.html stage-09/proposal_decision_state.json ``` -------------------------------- ### Run Stage 03: Search Strategy with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-b-literature-discovery.md Executes the SEARCH_STRATEGY stage using the specified config file and output directory. The --only-stage flag limits the run to this stage, and the output is written to runs/my-run. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage SEARCH_STRATEGY ``` -------------------------------- ### Run Stage 17: Paper Revision Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-g-paper-writing.md Executes the PAPER_REVISION stage using the specified config and output directory. Produces paper_revised.md in the stage-17 output folder. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage PAPER_REVISION ``` -------------------------------- ### Causal LM training with DataCollatorForLanguageModeling Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/transformers_training.md Sets up a GPT-style model with a data collator for causal language modeling (mlm=False). The Trainer uses the tokenized dataset and the collator. The model is loaded from 'gpt2'. ```python from transformers import AutoModelForCausalLM, DataCollatorForLanguageModeling model = AutoModelForCausalLM.from_pretrained("gpt2") data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False, # causal LM, not masked LM ) trainer = Trainer( model=model, args=args, train_dataset=tokenized_ds, data_collator=data_collator, ) ``` -------------------------------- ### Run Stage 07 Synthesis with scholarclaw run --only-stage SYNTHESIS Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-c-knowledge-synthesis.md Execute the SYNTHESIS stage for the ScholarClaw pipeline. Requires a config.yaml and an output directory. Restricts execution to just the synthesis stage. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage SYNTHESIS ``` -------------------------------- ### Run only a specific stage Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Run one specific step only, after a prior run exists. ```bash scholarclaw run -c config.yaml --output artifacts/your-run-folder --only-stage EXPERIMENT_DESIGN ``` -------------------------------- ### Validate and doctor ScholarClaw Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Check that everything works. If both commands finish without errors, you are ready to run. ```bash scholarclaw validate -c config.yaml scholarclaw doctor -c config.yaml ``` -------------------------------- ### Custom dataset registration JSON for data/dataset_info.json Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Shows the structure to register a custom dataset in data/dataset_info.json, mapping columns for the Alpaca format. ```json // data/dataset_info.json — register your dataset { "my_dataset": { "file_name": "my_data.json", "formatting": "alpaca", "columns": { "prompt": "instruction", "query": "input", "response": "output" } } } ``` -------------------------------- ### Run Stage 18 Quality Gate Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-h-finalization.md Run the Stage 18 quality gate. The first command runs without auto-approval; the second adds --auto-approve to skip manual gate approval. Use --only-stage QUALITY_GATE to execute just this gate stage. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage QUALITY_GATE scholarclaw run -c config.yaml --output runs/my-run --only-stage QUALITY_GATE --auto-approve ``` -------------------------------- ### Run external revision stage with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-j-external-revision.md Run the external revision stage. The first command executes the full revision bucket, while the second runs only the EXTERNAL_REVISION stage. Requires Stage 21 inputs (editor_decision.json, reviewers/, paper_final.md). ```bash scholarclaw run -c config.yaml --output runs/my-run --bucket revision scholarclaw run -c config.yaml --output runs/my-run --only-stage EXTERNAL_REVISION ``` -------------------------------- ### Run Stage 02: Problem Decompose with scholarclaw Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-a-research-scoping.md Command to run the PROBLEM_DECOMPOSE stage, specifying an output directory for the run. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage PROBLEM_DECOMPOSE ``` -------------------------------- ### Auto-approve Stage 9 with scholarclaw run Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/README.md Command to auto-approve the experiment design stage and run only that stage, using the --auto-approve flag. Replace YOUR-RUN-FOLDER with your output folder. ```bash scholarclaw run -c config.yaml \ --output artifacts/YOUR-RUN-FOLDER \ --only-stage EXPERIMENT_DESIGN \ --auto-approve ``` -------------------------------- ### Run Stage 11: Experiment Run Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-e-experiment-execution.md Executes the experiment run stage using the scholarclaw CLI. The --only-stage flag limits execution to the EXPERIMENT_RUN stage. Output is written to the specified directory. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage EXPERIMENT_RUN ``` -------------------------------- ### Run Stage 13 with scholarclaw CLI Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-f-analysis-decision.md Use this command to execute only the ANALYSIS_DECISION stage, specifying the config file and output directory. The --only-stage flag ensures only this stage runs. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage ANALYSIS_DECISION ``` -------------------------------- ### Run literature screening stage Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-b-literature-discovery.md Run the literature screening stage with the --only-stage flag. The second command adds --auto-approve for unattended execution. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage LITERATURE_SCREEN # unattended: scholarclaw run -c config.yaml --output runs/my-run --only-stage LITERATURE_SCREEN --auto-approve ``` -------------------------------- ### Export/merge LoRA adapter YAML configuration Source: https://github.com/asimsinan/scholarclaw/blob/main/scholarclaw/data/framework_docs/llamafactory.md Configuration for exporting and merging a LoRA adapter into a full model, specifying adapter path, export directory, shard size in GB, and legacy format option. ```yaml model_name_or_path: Qwen/Qwen2.5-3B adapter_name_or_path: ./output/checkpoint-1000 template: qwen finetuning_type: lora export_dir: ./merged_model export_size: 2 # shard size in GB export_legacy_format: false ``` -------------------------------- ### Set OpenRouter API key Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Set your OpenRouter API key in Terminal. Must be run in the same Terminal window each new session, or added to your shell profile. ```bash export OPENROUTER_API_KEY="your-key-here" ``` -------------------------------- ### Resume interrupted run Source: https://github.com/asimsinan/scholarclaw/blob/main/README.md Continue after interruption. ```bash scholarclaw run -c config.yaml --output artifacts/your-run-folder --resume --bucket proposal ``` -------------------------------- ### Run Stage 19 Export and Archive Source: https://github.com/asimsinan/scholarclaw/blob/main/docs/stages/phase-h-finalization.md Run Stage 19 to produce the final publication package, code bundle, archive, and bundle index. This stage is noncritical; failures can be skipped with --skip-noncritical-stage on full runs. ```bash scholarclaw run -c config.yaml --output runs/my-run --only-stage EXPORT_AND_ARCHIVE ```