{"id":17141067,"url":"https://github.com/zphang/minimal-llama","last_synced_at":"2025-04-05T18:10:42.119Z","repository":{"id":132749193,"uuid":"610519568","full_name":"zphang/minimal-llama","owner":"zphang","description":null,"archived":false,"fork":false,"pushed_at":"2023-10-15T20:40:09.000Z","size":297,"stargazers_count":458,"open_issues_count":11,"forks_count":45,"subscribers_count":17,"default_branch":"main","last_synced_at":"2025-03-29T17:11:15.062Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zphang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-06T23:51:04.000Z","updated_at":"2025-03-25T08:09:39.000Z","dependencies_parsed_at":"2023-10-16T12:25:35.591Z","dependency_job_id":"99320390-7072-44b5-8031-4250731646c6","html_url":"https://github.com/zphang/minimal-llama","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zphang%2Fminimal-llama","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zphang%2Fminimal-llama/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zphang%2Fminimal-llama/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zphang%2Fminimal-llama/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zphang","download_url":"https://codeload.github.com/zphang/minimal-llama/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247378149,"owners_count":20929297,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-14T20:24:15.181Z","updated_at":"2025-04-05T18:10:42.083Z","avatar_url":"https://github.com/zphang.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Minimal LLaMA\n\nThis repo contains a random assortment of code for running and fine-tuning LLaMA. Many parts are still work in progress. There ought to be more efficient methods of tuning (DeepSpeed / ZeRO, NeoX) than the ones presented here, but folks may find this useful already.\n\n- [Tokenize datasets](#tokenize-datasets)\n- [PEFT Fine-tuning with 8-bit](#peft-fine-tuning-with-8-bit)\n- [Fine-tuning with Naive Pipeline Parallel](#fine-tuning-with-naive-pipeline-parallel)\n- (New) [PEFT Fine-tuning with 8-bit and Pipeline Parallel](#peft-fine-tuning-with-8-bit-and-pipeline-parallel)\n- [Misc notes](#misc-notes)\n\nThis code was fairly quickly thrown together and may contains many, many bugs. Feedback is welcome!\n\n## Tokenize datasets\n\nFirst, we tokenize the data so we never have to worry about the tokenizer again. The tokenization script takes in a JSONL (each row containing the key `\"text\"` for the document text), and effectively concatenates, tokenizes, and slices into `max_seq_length` chunks.\n\n(This is a quick and dirty script that loads the whole dataset into memory.)\n\n```bash\npython tokenize_dataset.py \\\n    --tokenizer_path /path/to/tokenizer \\\n    --jsonl_path /path/to/data.jsonl \\\n    --save_path /path/to/tokenized_dataset \\\n    --max_seq_length 512\n```\n\n## PEFT Fine-tuning with 8-bit\n\n*Requires using the **Transformers** PR [here](https://github.com/huggingface/transformers/pull/21955/), based on the fork [here](https://github.com/zphang/transformers/tree/llama_push). Model weights need to be converted to HF format using the weight conversion script in the PR.*\n\n*Requires using the **PEFT** PR [here](https://github.com/huggingface/peft/pull/160), based on the fork [here](https://github.com/zphang/peft/tree/llama).*\n\n\nWe can fine-tune using the [PEFT](https://github.com/huggingface/peft) library, with the model converted to 8-bit. This is based on the guide [here](https://github.com/huggingface/peft#int8-training-of-large-models-in-colab-using-peft-lora-and-bits_and_bytes).\n\n```bash\npython finetune_peft.py \\\n    --model_path /path/to/llama-7b/ \\\n    --dataset_path /path/to/tokenized_dataset \\\n    --peft_mode lora \\\n    --lora_rank 8 \\\n    --per_device_train_batch_size 2 \\\n    --gradient_accumulation_steps 1 \\\n    --max_steps 2500 \\\n    --learning_rate 2e-4 \\\n    --fp16 \\\n    --logging_steps 10 \\\n    --output_dir /path/to/save\n```\n\nThe above configuration (with `max_seq_length=512`) uses about 20GB of RAM on a single GPU. (With bs=1 and `max_seq_length=256`, this gets down to about 12 GB.)\n\nYou can generate using the trained PEFT params using something like the following:\n\n```python\nimport torch\nimport transformers\nfrom finetune_peft import get_peft_config, PEFTArguments\nfrom peft import get_peft_model\n\nmodel_path = ...\npeft_path = ...\ntokenizer_path = ...\n\ntorch.set_default_tensor_type(torch.cuda.HalfTensor)\nmodel = transformers.LLaMAForCausalLM.from_pretrained(model_path)\npeft_config = get_peft_config(peft_args=PEFTArguments(peft_mode=\"lora\"))\nmodel = get_peft_model(model, peft_config)\nmodel.load_state_dict(torch.load(peft_path), strict=False)\ntorch.set_default_tensor_type(torch.cuda.FloatTensor)\n\ntokenizer = transformers.LLaMATokenizer.from_pretrained(tokenizer_path)\nbatch = tokenizer(\"The LLaMA language model is\", return_tensors=\"pt\")\n\nwith torch.no_grad():\n    out = model.generate(\n        input_ids=batch[\"input_ids\"],\n        attention_mask=torch.ones_like(batch[\"input_ids\"]),\n        max_length=200,\n    )\nprint(tokenizer.decode(out[0]))\n```\n\n## Fine-tuning with Naive Pipeline Parallel\n\n*Requires using the **Transformers** PR [here](https://github.com/huggingface/transformers/pull/21955/), based on the fork [here](https://github.com/zphang/transformers/tree/llama_push). Model weights need to be converted to HF format using the weight conversion script in the PR.*\n\n\nFor *fully* fine-tuning (larger) models, we can use (a very naively implemented version of) pipeline parallelism. This is preferable for larger models that won't fit on a single GPU.\n\n```bash\npython finetune_pp.py \\\n    --model_path /path/to/llama-7b/ \\\n    --dataset_path /path/to/tokenized_dataset \\\n    --save_dir /path/to/save \\\n    --batch_size 4 \\\n    --gradient_accumulation_steps 2 \\\n    --save_interval 2000 \\\n    --num_train_steps 20000\n```\n\nThe above configuration uses about 30-35GB of RAM per GPU across 8 GPUs.\n\n## PEFT Fine-tuning with 8-bit and Pipeline Parallel\n\n**Seems buggy, don't use this yet.**\n\n*Requires using the **Transformers** PR [here](https://github.com/huggingface/transformers/pull/21955/), based on the fork [here](https://github.com/zphang/transformers/tree/llama_push). Model weights need to be converted to HF format using the weight conversion script in the PR.*\n\n*Requires using the **PEFT** PR [here](https://github.com/huggingface/peft/pull/160), based on the fork [here](https://github.com/zphang/peft/tree/llama).*\n\nHere, we combine PEFT training with pipeline parallel to train with large models. See [PEFT Fine-tuning with 8-bit](#peft-fine-tuning-with-8-bit) for more details.\n\n```bash\npython finetune_pp_peft.py \\\n    --model_path /path/to/llama-30b/ \\\n    --dataset_path /path/to/tokenized_dataset \\\n    --save_dir /path/to/save \\\n    --batch_size 4 \\\n    --learning_rate 5e-5 \\\n    --gradient_accumulation_steps 1 \\\n    --save_interval 2000 \\\n    --num_train_steps 20000 \\\n    --peft_mode lora \\\n    --lora_rank 8\n```\n\nFor instance, you can fine-tune LoRA on 65B LLaMA with about 120GB of memory in total (e.g. 15GB each on 8 GPUs, or 60GB on 2 GPUs) with batch size=1 and sequence length = 512.\n\n## Misc Notes\n\n- I have no idea what hyperparameters are best for fine-tuning.\n- Aside from model parameters + gradients + optimizer states, the hidden activations also take up a big chunk of memory. Shortening the `max_sequence_length` is a good way of reducing memory consumption. I don't really know how much that affects fine-tuning performance either.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzphang%2Fminimal-llama","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzphang%2Fminimal-llama","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzphang%2Fminimal-llama/lists"}