# MarsLM MarsLM is a CPU-friendly decoder-only Transformer scaffold for building a small large language model from scratch on a laptop such as the HP 840 G5. ## 1. Arquitectura - Decoder-only Transformer with RoPE, RMSNorm, KV cache support, and efficient attention via PyTorch scaled dot-product attention. - The default configuration is a compact 100M-class model, but the code is parameterized to scale toward the 1B–3B range with larger hidden sizes and layers. ## 2. Tokenizador - SentencePiece BPE tokenizer. - Train it with the tokenizer script and point training/inference to the generated model file. ## 3. Dataset - The repository includes a downloader that can fetch public text and a tokenizer/preprocessing step that creates chunked tensor files. - A good starting point is Tiny Shakespeare or similar public corpora. ## 4. Entrenamiento - Training is implemented in PyTorch and supports CPU execution, gradient clipping, checkpointing, warmup, resume, and gradient accumulation for better learning stability. - To make the model learn better, use more data, keep the context window moderate, and train for more epochs rather than only increasing the batch size. ## 5. Inferencia - Generation is implemented through a simple autoregressive loop. ## 6. Cuantización - INT8 and INT4 export paths are included, plus a GGUF metadata stub for Ollama/llama.cpp workflows. ## 7. Optimización para HP 840 G5 - Set the thread count in the YAML config to match your CPU. - Use a small batch size, a modest context window, and save checkpoints often. - For CPU-only runs, prefer smaller model sizes and avoid large vocabularies. ## 8. Guía de ejecución 1. Install dependencies: `pip install -r requirements.txt` 2. Download a text corpus: `python datasets/download_dataset.py --output datasets/tiny.txt` 3. Train the tokenizer: `python tokenizer/train_tokenizer.py --input datasets/tiny.txt --model-prefix artifacts/tokenizer/marslm --vocab-size 32000` 4. Preprocess: `python datasets/preprocess.py --input datasets/tiny.txt --tokenizer artifacts/tokenizer/marslm.json --output artifacts/data/tokens.pt --block-size 512` 5. Train: `python training/train.py --config configs/marslm-100M.yaml --train-file artifacts/data/tokens.pt --tokenizer-model artifacts/tokenizer/marslm.json --output-dir artifacts/checkpoints --epochs 3 --batch-size 1 --gradient-accumulation-steps 4 --warmup-steps 50` 6. Generate text: `python inference/generate.py --model-path artifacts/checkpoints/marslm-final.pt --config artifacts/checkpoints/config.json --tokenizer-model artifacts/tokenizer/marslm.json` 7. Quantize: `python quantization/export_gguf.py --model-path artifacts/checkpoints/marslm-final.pt --output artifacts/quantized/model --quant-type int8` 8. Terminal y scripts: `docs/TerminalGuide.md` tiene los pasos y los scripts. ## 9. Configuración 5B y 10B - Se agregó `configs/marslm-5B.yaml` como referencia para una arquitectura de ~5B parámetros. - También se mantiene `configs/marslm-10B.yaml` como referencia para una arquitectura de ~10B parámetros. - Nota: entrenar un modelo de 5B o 10B en un HP 840 G5 con CPU no es práctico. Ambos requieren múltiples GPUs o un servicio de entrenamiento en la nube. - Usa estas configuraciones solo si puedes ejecutar el entrenamiento en un entorno de alta capacidad. ## 10. Preparar datos de Wikipedia - Coloca tus archivos de texto en `datasets/wikipedia/` o en cualquier carpeta nueva. - El pipeline ya está preparado para consumir varios archivos con el comando de preprocesado. - Ejemplo de uso: - `python datasets/download_dataset.py --output datasets/wikipedia/raw.txt --url https://...` - `python tokenizer/train_tokenizer.py --input datasets/wikipedia/*.txt --model-prefix artifacts/tokenizer/marslm --vocab-size 32000` - `python datasets/preprocess.py --input datasets/wikipedia/*.txt --tokenizer artifacts/tokenizer/marslm.json --output artifacts/data/tokens.pt --block-size 512` - `python training/train.py --config configs/marslm-5B.yaml --train-file artifacts/data/tokens.pt --tokenizer-model artifacts/tokenizer/marslm.json --output-dir artifacts/checkpoints` ## 10. Cómo hace que la IA aprenda - Aporta más texto de calidad: cuanto más datos limpios, mejor aprende el modelo. - Entrena más tiempo: si el corpus es bueno, 3-10 epochs suelen ayudar más que solo subir el batch size. - Usa un vocabulario razonable: 16k-32k tokens suele ser suficiente para un primer modelo local. - Ajusta el bloque de contexto: 512 o 1024 tokens son un buen punto de partida en CPU. - Revisa los checkpoints: si el loss baja y se estabiliza, el modelo aprende. ## 9. Mejoras opcionales - LoRA / QLoRA integration can be added later for faster fine-tuning. - Use Ollama with a converted GGUF artifact once the llama.cpp conversion step is available. ## 10. Hugging Face Spaces - La demo para Spaces queda lista con los archivos [app.py](app.py), [requirements.txt](requirements.txt) y [README_spaces.md](README_spaces.md). - Sube el repositorio completo a un nuevo Space con la opción "Gradio" como SDK. - Asegura que la carpeta [artifacts/checkpoints](artifacts/checkpoints) y [artifacts/tokenizer](artifacts/tokenizer) estén incluidas en el upload. - Una vez abierto el Space, la app se levantará automáticamente con el punto de entrada de Gradio.