{"id":"litgpt","name":"implementing-llms-litgpt","summary":"Lightning AIのLitGPTを用いて、20+の事前学習済みアーキテクチャ(Llama、Gemma、Phi、Qwen、Mistral)を用いてLLMを実装・訓練します。","body":"# LitGPT - Clean LLM Implementations\n\n## Quick start\n\nLitGPT provides 20+ pretrained LLM implementations with clean, readable code and production-ready training workflows.\n\n**Installation**:\n```bash\npip install 'litgpt[extra]'\n```\n\n**Load and use any model**:\n```python\nfrom litgpt import LLM\n\n# Load pretrained model\nllm = LLM.load(\"microsoft/phi-2\")\n\n# Generate text\nresult = llm.generate(\n    \"What is the capital of France?\",\n    max_new_tokens=50,\n    temperature=0.7\n)\nprint(result)\n```\n\n**List available models**:\n```bash\nlitgpt download list\n```\n\n## Common workflows\n\n### Workflow 1: Fine-tune on custom dataset\n\nCopy this checklist:\n\n```\nFine-Tuning Setup:\n- [ ] Step 1: Download pretrained model\n- [ ] Step 2: Prepare dataset\n- [ ] Step 3: Configure training\n- [ ] Step 4: Run fine-tuning\n```\n\n**Step 1: Download pretrained model**\n\n```bash\n# Download Llama 3 8B\nlitgpt download meta-llama/Meta-Llama-3-8B\n\n# Download Phi-2 (smaller, faster)\nlitgpt download microsoft/phi-2\n\n# Download Gemma 2B\nlitgpt download google/gemma-2b\n```\n\nModels are saved to `checkpoints/` directory.\n\n**Step 2: Prepare dataset**\n\nLitGPT supports multiple formats:\n\n**Alpaca format** (instruction-response):\n```json\n[\n  {\n    \"instruction\": \"What is the capital of France?\",\n    \"input\": \"\",\n    \"output\": \"The capital of France is Paris.\"\n  },\n  {\n    \"instruction\": \"Translate to Spanish: Hello, how are you?\",\n    \"input\": \"\",\n    \"output\": \"Hola, ¿cómo estás?\"\n  }\n]\n```\n\nSave as `data/my_dataset.json`.\n\n**Step 3: Configure training**\n\n```bash\n# Full fine-tuning (requires 40GB+ GPU for 7B models)\nlitgpt finetune \\\n  meta-llama/Meta-Llama-3-8B \\\n  --data JSON \\\n  --data.json_path data/my_dataset.json \\\n  --train.max_steps 1000 \\\n  --train.learning_rate 2e-5 \\\n  --train.micro_batch_size 1 \\\n  --train.global_batch_size 16\n\n# LoRA fine-tuning (efficient, 16GB GPU)\nlitgpt finetune_lora \\\n  microsoft/phi-2 \\\n  --data JSON \\\n  --data.json_path data/my_dataset.json \\\n  --lora_r 16 \\\n  --lora_alpha 32 \\\n  --lora_dropout 0.05 \\\n  --train.max_steps 1000 \\\n  --train.learning_rate 1e-4\n```\n\n**Step 4: Run fine-tuning**\n\nTraining saves checkpoints to `out/finetune/` automatically.\n\nMonitor training:\n```bash\n# View logs\ntail -f out/finetune/logs.txt\n\n# TensorBoard (if using --train.logger_name tensorboard)\ntensorboard --logdir out/finetune/lightning_logs\n```\n\n### Workflow 2: LoRA fine-tuning on single GPU\n\nMost memory-efficient option.\n\n```\nLoRA Training:\n- [ ] Step 1: Choose base model\n- [ ] Step 2: Configure LoRA parameters\n- [ ] Step 3: Train with LoRA\n- [ ] Step 4: Merge LoRA weights (optional)\n```\n\n**Step 1: Choose base model**\n\nFor limited GPU memory (12-16GB):\n- **Phi-2** (2.7B) - Best quality/size tradeoff\n- **Llama 3 1B** - Smallest, fastest\n- **Gemma 2B** - Good reasoning\n\n**Step 2: Configure LoRA parameters**\n\n```bash\nlitgpt finetune_lora \\\n  microsoft/phi-2 \\\n  --data JSON \\\n  --data.json_path data/my_dataset.json \\\n  --lora_r 16 \\          # LoRA rank (8-64, higher=more capacity)\n  --lora_alpha 32 \\      # LoRA scaling (typically 2×r)\n  --lora_dropout 0.05 \\  # Prevent overfitting\n  --lora_query true \\    # Apply LoRA to query projection\n  --lora_key false \\     # Usually not needed\n  --lora_value true \\    # Apply LoRA to value projection\n  --lora_projection true \\  # Apply LoRA to output projection\n  --lora_mlp false \\     # Usually not needed\n  --lora_head false      # Usually not needed\n```\n\nLoRA rank guide:\n- `r=8`: Lightweight, 2-4MB adapters\n- `r=16`: Standard, good quality\n- `r=32`: High capacity, use for complex tasks\n- `r=64`: Maximum quality, 4× larger adapters\n\n**Step 3: Train with LoRA**\n\n```bash\nlitgpt finetune_lora \\\n  microsoft/phi-2 \\\n  --data JSON \\\n  --data.json_path data/my_dataset.json \\\n  --lora_r 16 \\\n  --train.epochs 3 \\\n  --train.learning_rate 1e-4 \\\n  --train.micro_batch_size 4 \\\n  --train.global_batch_size 32 \\\n  --out_dir out/phi2-lora\n\n# Memory usage: ~8-12GB for Phi-2 with LoRA\n```\n\n**Step 4: Merge LoRA weights** (optional)\n\nMerge LoRA adapters into base model for deployment:\n\n```bash\nlitgpt merge_lora \\\n  out/phi2-lora/final \\\n  --out_dir out/phi2-merged\n```\n\nNow use merged model:\n```python\nfrom litgpt import LLM\nllm = LLM.load(\"out/phi2-merged\")\n```\n\n### Workflow 3: Pretrain from scratch\n\nTrain new model on your domain data.\n\n```\nPretraining:\n- [ ] Step 1: Prepare pretraining dataset\n- [ ] Step 2: Configure model architecture\n- [ ] Step 3: Set up multi-GPU training\n- [ ] Step 4: Launch pretraining\n```\n\n**Step 1: Prepare pretraining dataset**\n\nLitGPT expects tokenized data. Use `prepare_dataset.py`:\n\n```bash\npython scripts/prepare_dataset.py \\\n  --source_path data/my_corpus.txt \\\n  --checkpoint_dir checkpoints/tokenizer \\\n  --destination_path data/pretrain \\\n  --split train,val\n```\n\n**Step 2: Configure model architecture**\n\nEdit config file or use existing:\n\n```python\n# config/pythia-160m.yaml\nmodel_name: pythia-160m\nblock_size: 2048\nvocab_size: 50304\nn_layer: 12\nn_head: 12\nn_embd: 768\nrotary_percentage: 0.25\nparallel_residual: true\nbias: true\n```\n\n**Step 3: Set up multi-GPU training**\n\n```bash\n# Single GPU\nlitgpt pretrain \\\n  --config config/pythia-160m.yaml \\\n  --data.data_dir data/pretrain \\\n  --train.max_tokens 10_000_000_000\n\n# Multi-GPU with FSDP\nlitgpt pretrain \\\n  --config config/pythia-1b.yaml \\\n  --data.data_dir data/pretrain \\\n  --devices 8 \\\n  --train.max_tokens 100_000_000_000\n```\n\n**Step 4: Launch pretraining**\n\nFor large-scale pretraining on cluster:\n\n```bash\n# Using SLURM\nsbatch --nodes=8 --gpus-per-node=8 \\\n  pretrain_script.sh\n\n# pretrain_script.sh content:\nlitgpt pretrain \\\n  --config config/pythia-1b.yaml \\\n  --data.data_dir /shared/data/pretrain \\\n  --devices 8 \\\n  --num_nodes 8 \\\n  --train.global_batch_size 512 \\\n  --train.max_tokens 300_000_000_000\n```\n\n### Workflow 4: Convert and deploy model\n\nExport LitGPT models for production.\n\n```\nModel Deployment:\n- [ ] Step 1: Test inference locally\n- [ ] Step 2: Quantize model (optional)\n- [ ] Step 3: Convert to GGUF (for llama.cpp)\n- [ ] Step 4: Deploy with API\n```\n\n**Step 1: Test inference locally**\n\n```python\nfrom litgpt import LLM\n\nllm = LLM.load(\"out/phi2-lora/final\")\n\n# Single generation\nprint(llm.generate(\"What is machine learning?\"))\n\n# Streaming\nfor token in llm.generate(\"Explain quantum computing\", stream=True):\n    print(token, end=\"\", flush=True)\n\n# Batch inference\nprompts = [\"Hello\", \"Goodbye\", \"Thank you\"]\nresults = [llm.generate(p) for p in prompts]\n```\n\n**Step 2: Quantize model** (optional)\n\nReduce model size with minimal quality loss:\n\n```bash\n# 8-bit quantization (50% size reduction)\nlitgpt convert_lit_checkpoint \\\n  out/phi2-lora/final \\\n  --dtype bfloat16 \\\n  --quantize bnb.nf4\n\n# 4-bit quantization (75% size reduction)\nlitgpt convert_lit_checkpoint \\\n  out/phi2-lora/final \\\n  --quantize bnb.nf4-dq  # Double quantization\n```\n\n**Step 3: Convert to GGUF** (for llama.cpp)\n\n```bash\npython scripts/convert_lit_checkpoint.py \\\n  --checkpoint_path out/phi2-lora/final \\\n  --output_path models/phi2.gguf \\\n  --model_name microsoft/phi-2\n```\n\n**Step 4: Deploy with API**\n\n```python\nfrom fastapi import FastAPI\nfrom litgpt import LLM\n\napp = FastAPI()\nllm = LLM.load(\"out/phi2-lora/final\")\n\n@app.post(\"/generate\")\ndef generate(prompt: str, max_tokens: int = 100):\n    result = llm.generate(\n        prompt,\n        max_new_tokens=max_tokens,\n        temperature=0.7\n    )\n    return {\"response\": result}\n\n# Run: uvicorn api:app --host 0.0.0.0 --port 8000\n```\n\n## When to use vs alternatives\n\n**Use LitGPT when:**\n- Want to understand LLM architectures (clean, readable code)\n- Need production-ready training recipes\n- Educational purposes or research\n- Prototyping new model ideas\n- Lightning ecosystem user\n\n**Use alternatives instead:**\n- **Axolotl/TRL**: More fine-tuning features, YAML configs\n- **Megatron-Core**: Maximum performance for >70B models\n- **HuggingFace Transformers**: Broadest model support\n- **vLLM**: Inference-only (no training)\n\n## Common issues\n\n**Issue: Out of memory during fine-tuning**\n\nUse LoRA instead of full fine-tuning:\n```bash\n# Instead of litgpt finetune (requires 40GB+)\nlitgpt finetune_lora  # Only needs 12-16GB\n```\n\nOr enable gradient checkpointing:\n```bash\nlitgpt finetune_lora \\\n  ... \\\n  --train.gradient_accumulation_iters 4  # Accumulate gradients\n```\n\n**Issue: Training too slow**\n\nEnable Flash Attention (built-in, automatic on compatible hardware):\n```python\n# Already enabled by default on Ampere+ GPUs (A100, RTX 30/40 series)\n# No configuration needed\n```\n\nUse smaller micro-batch and accumulate:\n```bash\n--train.micro_batch_size 1 \\\n--train.global_batch_size 32 \\\n--train.gradient_accumulation_iters 32  # Effective batch=32\n```\n\n**Issue: Model not loading**\n\nCheck model name:\n```bash\n# List all available models\nlitgpt download list\n\n# Download if not exists\nlitgpt download meta-llama/Meta-Llama-3-8B\n```\n\nVerify checkpoints directory:\n```bash\nls checkpoints/\n# Should see: meta-llama/Meta-Llama-3-8B/\n```\n\n**Issue: LoRA adapters too large**\n\nReduce LoRA rank:\n```bash\n--lora_r 8  # Instead of 16 or 32\n```\n\nApply LoRA to fewer layers:\n```bash\n--lora_query true \\\n--lora_value true \\\n--lora_projection false \\  # Disable this\n--lora_mlp false  # And this\n```\n\n## Advanced topics\n\n**Supported architectures**: See [references/supported-models.md](references/supported-models.md) for complete list of 20+ model families with sizes and capabilities.\n\n**Training recipes**: See [references/training-recipes.md](references/training-recipes.md) for proven hyperparameter configurations for pretraining and fine-tuning.\n\n**FSDP configuration**: See [references/distributed-training.md](references/distributed-training.md) for multi-GPU training with Fully Sharded Data Parallel.\n\n**Custom architectures**: See [references/custom-models.md](references/custom-models.md) for implementing new model architectures in LitGPT style.\n\n## Hardware requirements\n\n- **GPU**: NVIDIA (CUDA 11.8+), AMD (ROCm), Apple Silicon (MPS)\n- **Memory**:\n  - Inference (Phi-2): 6GB\n  - LoRA fine-tuning (7B): 16GB\n  - Full fine-tuning (7B): 40GB+\n  - Pretraining (1B): 24GB\n- **Storage**: 5-50GB per model (depending on size)\n\n## Resources\n\n- GitHub: https://github.com/Lightning-AI/litgpt\n- Docs: https://lightning.ai/docs/litgpt\n- Tutorials: https://lightning.ai/docs/litgpt/tutorials\n- Model zoo: 20+ pretrained architectures (Llama, Gemma, Phi, Qwen, Mistral, Mixtral, Falcon, etc.)","author":"@Orchestra-Research","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/Orchestra-Research/AI-Research-SKILLs/tree/main/01-model-architecture/litgpt","license":"MIT","category":"writing","lang":"en","tokens":3065,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/custom-models.md","size":15655,"sha256":"82a300cde9db77031d7371edc9c689ad6399b5f0a5b5180e0ce3ac2830265014"},{"path":"references/distributed-training.md","size":11099,"sha256":"44a74c9bf640159e3e11bd885a21c65d96c6fbd7471da802979ba75fab8ec073"},{"path":"references/supported-models.md","size":7935,"sha256":"9d8d6632fb43b0d4673ef19403a1672e0479415da46241fe24a956bcb6644a31"},{"path":"references/training-recipes.md","size":10978,"sha256":"90bad095a8c3e87f221e45c66712b26bf096cf09b233db4c8340e540aacab25e"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[{"code":"code.eval","kind":"dangerous-code","where":"references/custom-models.md:404","excerpt":"eval(","message":"evaluates code at runtime","severity":"warn"}],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["lightning.ai"]}}