Upload 56 files
Browse files- README.md +11 -1
- configs/marslm-100M.yaml +1 -0
- configs/marslm-1B.yaml +20 -0
- configs/marslm-300M.yaml +1 -4
- configs/marslm-500M.yaml +20 -0
- configs/marslm-700M-chat.yaml +29 -0
- configs/marslm-700M-v2.yaml +28 -0
- configs/marslm-700M.yaml +27 -0
- datasets/__init__.py +1 -0
- datasets/__pycache__/__init__.cpython-314.pyc +0 -0
- datasets/__pycache__/instruction.cpython-314.pyc +0 -0
- datasets/__pycache__/preprocess.cpython-314.pyc +0 -0
- datasets/__pycache__/streaming.cpython-314.pyc +0 -0
- datasets/instruction.py +91 -0
- datasets/preprocess.py +32 -11
- datasets/streaming.py +194 -0
- datasets/tiny.txt +0 -0
- docs/TerminalGuide.md +1 -0
- docs/llama_cpp_integration.md +57 -0
- evaluation/__init__.py +4 -0
- evaluation/__pycache__/evaluate.cpython-314.pyc +0 -0
- evaluation/__pycache__/metrics.cpython-314.pyc +0 -0
- evaluation/evaluate.py +112 -0
- evaluation/metrics.py +33 -0
- export/__init__.py +3 -0
- export/__pycache__/export.cpython-314.pyc +0 -0
- export/export.py +74 -0
- requirements.txt +2 -1
- scripts/chat_model.ps1 +19 -0
- scripts/export_llama_cpp.ps1 +20 -0
- scripts/generate_yaml.py +105 -0
- tests/__pycache__/test_inference_cases.cpython-314.pyc +0 -0
- tests/test_inference_cases.py +58 -0
- training/__pycache__/instruction_train.cpython-314.pyc +0 -0
- training/__pycache__/train.cpython-314.pyc +0 -0
- training/instruction_train.py +167 -0
- training/train.py +107 -49
README.md
CHANGED
|
@@ -24,7 +24,17 @@ MarsLM is a CPU-friendly decoder-only Transformer scaffold for building a small
|
|
| 24 |
## 6. Cuantización
|
| 25 |
- INT8 and INT4 export paths are included, plus a GGUF metadata stub for Ollama/llama.cpp workflows.
|
| 26 |
|
| 27 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
- Set the thread count in the YAML config to match your CPU.
|
| 29 |
- Use a small batch size, a modest context window, and save checkpoints often.
|
| 30 |
- For CPU-only runs, prefer smaller model sizes and avoid large vocabularies.
|
|
|
|
| 24 |
## 6. Cuantización
|
| 25 |
- INT8 and INT4 export paths are included, plus a GGUF metadata stub for Ollama/llama.cpp workflows.
|
| 26 |
|
| 27 |
+
## 8. Evaluación y exportación
|
| 28 |
+
- Nueva evaluación de checkpoints con `evaluation/evaluate.py`.
|
| 29 |
+
- Calcula pérdidas, perplexity y throughput de tokens para conjuntos de evaluación en TXT o JSONL.
|
| 30 |
+
- Exporta checkpoints a `pt`, `safetensors` y `gguf` con `export/export.py`.
|
| 31 |
+
|
| 32 |
+
## 9. Flash Attention y GPU
|
| 33 |
+
- Habilita Flash Attention con `model.use_flash_attention: true` en tu archivo YAML de configuración.
|
| 34 |
+
- Requiere `xformers`; en CPU o si `xformers` no está disponible, la atención causal de PyTorch se usa como respaldo.
|
| 35 |
+
- Si no deseas usar Flash Attention, deja `use_flash_attention: false`.
|
| 36 |
+
|
| 37 |
+
## 10. Optimización para HP 840 G5
|
| 38 |
- Set the thread count in the YAML config to match your CPU.
|
| 39 |
- Use a small batch size, a modest context window, and save checkpoints often.
|
| 40 |
- For CPU-only runs, prefer smaller model sizes and avoid large vocabularies.
|
configs/marslm-100M.yaml
CHANGED
|
@@ -7,6 +7,7 @@ model:
|
|
| 7 |
max_position_embeddings: 2048
|
| 8 |
dropout: 0.0
|
| 9 |
rope_theta: 10000.0
|
|
|
|
| 10 |
training:
|
| 11 |
batch_size: 2
|
| 12 |
epochs: 1
|
|
|
|
| 7 |
max_position_embeddings: 2048
|
| 8 |
dropout: 0.0
|
| 9 |
rope_theta: 10000.0
|
| 10 |
+
use_flash_attention: false
|
| 11 |
training:
|
| 12 |
batch_size: 2
|
| 13 |
epochs: 1
|
configs/marslm-1B.yaml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
model_size: 1B
|
| 3 |
+
vocab_size: 32000
|
| 4 |
+
max_position_embeddings: 4096
|
| 5 |
+
dropout: 0.0
|
| 6 |
+
rope_theta: 10000.0
|
| 7 |
+
|
| 8 |
+
training:
|
| 9 |
+
batch_size: 1
|
| 10 |
+
epochs: 5
|
| 11 |
+
learning_rate: 0.00015
|
| 12 |
+
weight_decay: 0.01
|
| 13 |
+
block_size: 512
|
| 14 |
+
checkpoint_interval: 200
|
| 15 |
+
gradient_accumulation_steps: 16
|
| 16 |
+
warmup_steps: 1500
|
| 17 |
+
|
| 18 |
+
system:
|
| 19 |
+
device: auto
|
| 20 |
+
torch_threads: 4
|
configs/marslm-300M.yaml
CHANGED
|
@@ -1,9 +1,6 @@
|
|
| 1 |
model:
|
|
|
|
| 2 |
vocab_size: 20000
|
| 3 |
-
hidden_size: 1024
|
| 4 |
-
intermediate_size: 2816
|
| 5 |
-
num_hidden_layers: 16
|
| 6 |
-
num_attention_heads: 16
|
| 7 |
max_position_embeddings: 2048
|
| 8 |
dropout: 0.0
|
| 9 |
rope_theta: 10000.0
|
|
|
|
| 1 |
model:
|
| 2 |
+
model_size: 300M
|
| 3 |
vocab_size: 20000
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
max_position_embeddings: 2048
|
| 5 |
dropout: 0.0
|
| 6 |
rope_theta: 10000.0
|
configs/marslm-500M.yaml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
model_size: 500M
|
| 3 |
+
vocab_size: 32000
|
| 4 |
+
max_position_embeddings: 4096
|
| 5 |
+
dropout: 0.0
|
| 6 |
+
rope_theta: 10000.0
|
| 7 |
+
|
| 8 |
+
training:
|
| 9 |
+
batch_size: 1
|
| 10 |
+
epochs: 5
|
| 11 |
+
learning_rate: 0.00015
|
| 12 |
+
weight_decay: 0.01
|
| 13 |
+
block_size: 512
|
| 14 |
+
checkpoint_interval: 200
|
| 15 |
+
gradient_accumulation_steps: 8
|
| 16 |
+
warmup_steps: 1000
|
| 17 |
+
|
| 18 |
+
system:
|
| 19 |
+
device: auto
|
| 20 |
+
torch_threads: 4
|
configs/marslm-700M-chat.yaml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
vocab_size: 32000
|
| 3 |
+
hidden_size: 1536
|
| 4 |
+
intermediate_size: 6144
|
| 5 |
+
num_hidden_layers: 24
|
| 6 |
+
num_attention_heads: 16
|
| 7 |
+
num_key_value_heads: 8
|
| 8 |
+
max_position_embeddings: 8192
|
| 9 |
+
dropout: 0.0
|
| 10 |
+
rope_theta: 10000.0
|
| 11 |
+
use_flash_attention: false
|
| 12 |
+
gradient_checkpointing: false
|
| 13 |
+
tie_word_embeddings: true
|
| 14 |
+
training:
|
| 15 |
+
batch_size: 1
|
| 16 |
+
epochs: 2
|
| 17 |
+
learning_rate: 0.0001
|
| 18 |
+
weight_decay: 0.0
|
| 19 |
+
block_size: 1024
|
| 20 |
+
checkpoint_interval: 100
|
| 21 |
+
gradient_accumulation_steps: 4
|
| 22 |
+
warmup_steps: 50
|
| 23 |
+
use_fp16: false
|
| 24 |
+
eval_batch_size: 1
|
| 25 |
+
eval_interval: 0
|
| 26 |
+
max_steps: 0
|
| 27 |
+
system:
|
| 28 |
+
device: auto
|
| 29 |
+
torch_threads: 4
|
configs/marslm-700M-v2.yaml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
vocab_size: 32000
|
| 3 |
+
hidden_size: 1536
|
| 4 |
+
intermediate_size: 6144
|
| 5 |
+
num_hidden_layers: 24
|
| 6 |
+
num_attention_heads: 16
|
| 7 |
+
num_key_value_heads: 8
|
| 8 |
+
max_position_embeddings: 8192
|
| 9 |
+
dropout: 0.0
|
| 10 |
+
rope_theta: 10000.0
|
| 11 |
+
use_flash_attention: false
|
| 12 |
+
gradient_checkpointing: false
|
| 13 |
+
tie_word_embeddings: true
|
| 14 |
+
training:
|
| 15 |
+
batch_size: 1
|
| 16 |
+
epochs: 3
|
| 17 |
+
learning_rate: 0.00015
|
| 18 |
+
weight_decay: 0.01
|
| 19 |
+
block_size: 4096
|
| 20 |
+
checkpoint_interval: 100
|
| 21 |
+
gradient_accumulation_steps: 4
|
| 22 |
+
warmup_steps: 50
|
| 23 |
+
use_fp16: false
|
| 24 |
+
eval_batch_size: 1
|
| 25 |
+
eval_interval: 0
|
| 26 |
+
system:
|
| 27 |
+
device: auto
|
| 28 |
+
torch_threads: 4
|
configs/marslm-700M.yaml
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
model_size: 700M
|
| 3 |
+
vocab_size: 32000
|
| 4 |
+
max_position_embeddings: 4096
|
| 5 |
+
dropout: 0.0
|
| 6 |
+
rope_theta: 10000.0
|
| 7 |
+
|
| 8 |
+
training:
|
| 9 |
+
# Entrenamiento
|
| 10 |
+
epochs: 10
|
| 11 |
+
batch_size: 1
|
| 12 |
+
learning_rate: 0.00015
|
| 13 |
+
weight_decay: 0.01
|
| 14 |
+
|
| 15 |
+
# Datos
|
| 16 |
+
block_size: 512
|
| 17 |
+
|
| 18 |
+
# Checkpoints
|
| 19 |
+
checkpoint_interval: 100
|
| 20 |
+
|
| 21 |
+
# Optimización
|
| 22 |
+
gradient_accumulation_steps: 32
|
| 23 |
+
warmup_steps: 1000
|
| 24 |
+
|
| 25 |
+
system:
|
| 26 |
+
device: auto
|
| 27 |
+
torch_threads: 4
|
datasets/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Local datasets package for MarsLM project."""
|
datasets/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (224 Bytes). View file
|
|
|
datasets/__pycache__/instruction.cpython-314.pyc
ADDED
|
Binary file (7.27 kB). View file
|
|
|
datasets/__pycache__/preprocess.cpython-314.pyc
CHANGED
|
Binary files a/datasets/__pycache__/preprocess.cpython-314.pyc and b/datasets/__pycache__/preprocess.cpython-314.pyc differ
|
|
|
datasets/__pycache__/streaming.cpython-314.pyc
ADDED
|
Binary file (13.2 kB). View file
|
|
|
datasets/instruction.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.utils.data import IterableDataset
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import datasets
|
| 10 |
+
except ImportError: # type: ignore
|
| 11 |
+
datasets = None # type: ignore
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _extract_instruction_field(item: Dict[str, Any]) -> Optional[str]:
|
| 15 |
+
for key in ["instruction", "prompt", "task", "query"]:
|
| 16 |
+
value = item.get(key)
|
| 17 |
+
if isinstance(value, str) and value.strip():
|
| 18 |
+
return value.strip()
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _extract_output_field(item: Dict[str, Any]) -> Optional[str]:
|
| 23 |
+
for key in ["output", "response", "completion", "answer", "reply"]:
|
| 24 |
+
value = item.get(key)
|
| 25 |
+
if isinstance(value, str) and value.strip():
|
| 26 |
+
return value.strip()
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _load_jsonl_examples(path: Path) -> Iterator[Dict[str, Any]]:
|
| 31 |
+
with path.open("r", encoding="utf-8", errors="ignore") as handle:
|
| 32 |
+
for line in handle:
|
| 33 |
+
if not line.strip():
|
| 34 |
+
continue
|
| 35 |
+
try:
|
| 36 |
+
payload = json.loads(line)
|
| 37 |
+
if isinstance(payload, dict):
|
| 38 |
+
yield payload
|
| 39 |
+
except json.JSONDecodeError:
|
| 40 |
+
continue
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _load_hf_dataset(dataset_name: str, split: str = "train") -> Iterator[Dict[str, Any]]:
|
| 44 |
+
if datasets is None:
|
| 45 |
+
raise RuntimeError("The datasets library is required to load Hugging Face datasets")
|
| 46 |
+
dataset = datasets.load_dataset(dataset_name, split=split, streaming=True)
|
| 47 |
+
for item in dataset:
|
| 48 |
+
if isinstance(item, dict):
|
| 49 |
+
yield item
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class InstructionTuningDataset(IterableDataset):
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
sources: Sequence[Union[str, Path]],
|
| 56 |
+
tokenizer: Any,
|
| 57 |
+
block_size: int = 1024,
|
| 58 |
+
prompt_template: str = "### Instruction:\n{instruction}\n\n### Response:\n{response}",
|
| 59 |
+
):
|
| 60 |
+
self.sources = sources
|
| 61 |
+
self.tokenizer = tokenizer
|
| 62 |
+
self.block_size = block_size
|
| 63 |
+
self.prompt_template = prompt_template
|
| 64 |
+
|
| 65 |
+
def _iter_source(self, source: Union[str, Path]) -> Iterator[Dict[str, Any]]:
|
| 66 |
+
if isinstance(source, Path) and source.exists():
|
| 67 |
+
if source.suffix == ".jsonl":
|
| 68 |
+
yield from _load_jsonl_examples(source)
|
| 69 |
+
else:
|
| 70 |
+
raise ValueError("Instruction tuning requires a JSONL file or a Hugging Face dataset identifier")
|
| 71 |
+
else:
|
| 72 |
+
yield from _load_hf_dataset(str(source))
|
| 73 |
+
|
| 74 |
+
def _format_example(self, item: Dict[str, Any]) -> Optional[str]:
|
| 75 |
+
instruction = _extract_instruction_field(item)
|
| 76 |
+
response = _extract_output_field(item)
|
| 77 |
+
if instruction is None or response is None:
|
| 78 |
+
return None
|
| 79 |
+
return self.prompt_template.format(instruction=instruction, response=response)
|
| 80 |
+
|
| 81 |
+
def __iter__(self) -> Iterator[torch.Tensor]:
|
| 82 |
+
for source in self.sources:
|
| 83 |
+
for item in self._iter_source(source):
|
| 84 |
+
text = self._format_example(item)
|
| 85 |
+
if not text:
|
| 86 |
+
continue
|
| 87 |
+
token_ids = self.tokenizer.encode(text, add_special_tokens=False).ids
|
| 88 |
+
if len(token_ids) < 2:
|
| 89 |
+
continue
|
| 90 |
+
token_ids = token_ids[: self.block_size]
|
| 91 |
+
yield torch.tensor(token_ids, dtype=torch.long)
|
datasets/preprocess.py
CHANGED
|
@@ -11,19 +11,40 @@ if str(ROOT) not in sys.path:
|
|
| 11 |
from tokenizer.tokenizer_utils import load_tokenizer, encode_text
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def preprocess_dataset(input_paths, tokenizer_path, output_path, block_size=512):
|
| 15 |
tokenizer = load_tokenizer(tokenizer_path)
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
def main():
|
|
|
|
| 11 |
from tokenizer.tokenizer_utils import load_tokenizer, encode_text
|
| 12 |
|
| 13 |
|
| 14 |
+
def _stream_lines(paths):
|
| 15 |
+
for path in [Path(p) for p in paths]:
|
| 16 |
+
if path.suffix == ".jsonl":
|
| 17 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 18 |
+
for line in handle:
|
| 19 |
+
yield line.strip()
|
| 20 |
+
else:
|
| 21 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 22 |
+
for line in handle:
|
| 23 |
+
yield line
|
| 24 |
+
|
| 25 |
+
|
| 26 |
def preprocess_dataset(input_paths, tokenizer_path, output_path, block_size=512):
|
| 27 |
tokenizer = load_tokenizer(tokenizer_path)
|
| 28 |
+
output_path = Path(output_path)
|
| 29 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
buffer = []
|
| 32 |
+
chunk_count = 0
|
| 33 |
+
for text in _stream_lines(input_paths):
|
| 34 |
+
if not text:
|
| 35 |
+
continue
|
| 36 |
+
ids = encode_text(tokenizer, text, add_special_tokens=False)
|
| 37 |
+
buffer.extend(ids)
|
| 38 |
+
while len(buffer) >= block_size:
|
| 39 |
+
chunk = torch.tensor(buffer[:block_size], dtype=torch.long)
|
| 40 |
+
chunk_file = output_path.parent / f"chunk-{chunk_count:06d}.pt"
|
| 41 |
+
torch.save({"tokens": chunk}, chunk_file)
|
| 42 |
+
chunk_count += 1
|
| 43 |
+
buffer = buffer[block_size:]
|
| 44 |
+
|
| 45 |
+
if chunk_count == 0:
|
| 46 |
+
raise ValueError("No data could be written. Check the input corpus and block_size.")
|
| 47 |
+
print(f"Saved {chunk_count} chunks to {output_path.parent}")
|
| 48 |
|
| 49 |
|
| 50 |
def main():
|
datasets/streaming.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Union
|
| 4 |
+
from urllib.parse import urlparse
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import IterableDataset
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import requests
|
| 11 |
+
except ImportError: # type: ignore
|
| 12 |
+
requests = None # type: ignore
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import datasets
|
| 16 |
+
except ImportError: # type: ignore
|
| 17 |
+
datasets = None # type: ignore
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _read_text_lines(path: Path) -> Iterator[str]:
|
| 21 |
+
with path.open("r", encoding="utf-8", errors="ignore") as handle:
|
| 22 |
+
for line in handle:
|
| 23 |
+
yield line.rstrip("\n")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _read_jsonl_lines(path: Path) -> Iterator[str]:
|
| 27 |
+
with path.open("r", encoding="utf-8", errors="ignore") as handle:
|
| 28 |
+
for line in handle:
|
| 29 |
+
if not line.strip():
|
| 30 |
+
continue
|
| 31 |
+
try:
|
| 32 |
+
payload = json.loads(line)
|
| 33 |
+
if isinstance(payload, dict):
|
| 34 |
+
text = payload.get("text") or payload.get("content") or payload.get("sentence")
|
| 35 |
+
if isinstance(text, str):
|
| 36 |
+
yield text
|
| 37 |
+
continue
|
| 38 |
+
yield line.strip()
|
| 39 |
+
except json.JSONDecodeError:
|
| 40 |
+
yield line.strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _load_parquet_examples(path: Path) -> Iterator[str]:
|
| 44 |
+
if datasets is None:
|
| 45 |
+
raise RuntimeError("The datasets library is required to load Parquet datasets")
|
| 46 |
+
dataset = datasets.load_dataset("parquet", data_files=str(path), split="train", streaming=True)
|
| 47 |
+
for item in dataset:
|
| 48 |
+
text = _extract_text(item)
|
| 49 |
+
if text is not None:
|
| 50 |
+
yield text
|
| 51 |
+
continue
|
| 52 |
+
yield str(item)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _is_http_url(source: str) -> bool:
|
| 56 |
+
parsed = urlparse(source)
|
| 57 |
+
return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _load_http_text(url: str) -> Iterator[str]:
|
| 61 |
+
if requests is None:
|
| 62 |
+
raise RuntimeError("The requests library is required to load text from HTTP URLs")
|
| 63 |
+
with requests.get(url, stream=True, timeout=30) as response:
|
| 64 |
+
response.raise_for_status()
|
| 65 |
+
for line in response.iter_lines(decode_unicode=True):
|
| 66 |
+
if not line:
|
| 67 |
+
continue
|
| 68 |
+
yield line.strip()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _extract_text(item: Any) -> Optional[str]:
|
| 72 |
+
if isinstance(item, str):
|
| 73 |
+
return item
|
| 74 |
+
if not isinstance(item, dict):
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
keys = [
|
| 78 |
+
"text",
|
| 79 |
+
"content",
|
| 80 |
+
"sentence",
|
| 81 |
+
"article",
|
| 82 |
+
"body",
|
| 83 |
+
"document",
|
| 84 |
+
"prompt",
|
| 85 |
+
"completion",
|
| 86 |
+
"source",
|
| 87 |
+
"raw_text",
|
| 88 |
+
]
|
| 89 |
+
for key in keys:
|
| 90 |
+
value = item.get(key)
|
| 91 |
+
if isinstance(value, str) and value.strip():
|
| 92 |
+
return value
|
| 93 |
+
|
| 94 |
+
text_fields = [v for v in item.values() if isinstance(v, str) and v.strip()]
|
| 95 |
+
if text_fields:
|
| 96 |
+
return text_fields[0]
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _load_hf_dataset(dataset_name: str, split: str = "train") -> Iterator[str]:
|
| 101 |
+
if datasets is None:
|
| 102 |
+
raise RuntimeError("The datasets library is required to load Hugging Face datasets")
|
| 103 |
+
dataset = datasets.load_dataset(dataset_name, split=split, streaming=True)
|
| 104 |
+
for item in dataset:
|
| 105 |
+
text = _extract_text(item)
|
| 106 |
+
if text is not None:
|
| 107 |
+
yield text
|
| 108 |
+
continue
|
| 109 |
+
yield str(item)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class MarsLMStreamingDataset(IterableDataset):
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
input_sources: Sequence[Union[str, Path]],
|
| 116 |
+
tokenizer: Any,
|
| 117 |
+
block_size: int = 512,
|
| 118 |
+
use_special_tokens: bool = False,
|
| 119 |
+
):
|
| 120 |
+
self.input_sources: List[Union[str, Path]] = []
|
| 121 |
+
for src in input_sources:
|
| 122 |
+
if isinstance(src, str) and _is_http_url(src):
|
| 123 |
+
self.input_sources.append(src)
|
| 124 |
+
elif isinstance(src, Path):
|
| 125 |
+
self.input_sources.append(src)
|
| 126 |
+
else:
|
| 127 |
+
try:
|
| 128 |
+
candidate = Path(src)
|
| 129 |
+
self.input_sources.append(candidate)
|
| 130 |
+
except TypeError:
|
| 131 |
+
self.input_sources.append(src)
|
| 132 |
+
self.tokenizer = tokenizer
|
| 133 |
+
self.block_size = block_size
|
| 134 |
+
self.use_special_tokens = use_special_tokens
|
| 135 |
+
|
| 136 |
+
def _iter_source(self, source: Path) -> Iterator[str]:
|
| 137 |
+
if source.suffix == ".jsonl":
|
| 138 |
+
yield from _read_jsonl_lines(source)
|
| 139 |
+
elif source.suffix == ".parquet":
|
| 140 |
+
yield from _load_parquet_examples(source)
|
| 141 |
+
else:
|
| 142 |
+
yield from _read_text_lines(source)
|
| 143 |
+
|
| 144 |
+
def _iter_hf_dataset(self, source: str) -> Iterator[str]:
|
| 145 |
+
yield from _load_hf_dataset(source)
|
| 146 |
+
|
| 147 |
+
def _text_iterator(self) -> Iterator[str]:
|
| 148 |
+
for source in self.input_sources:
|
| 149 |
+
if isinstance(source, Path):
|
| 150 |
+
if source.exists():
|
| 151 |
+
yield from self._iter_source(source)
|
| 152 |
+
else:
|
| 153 |
+
yield from self._iter_hf_dataset(source.as_posix())
|
| 154 |
+
elif isinstance(source, str) and _is_http_url(source):
|
| 155 |
+
yield from _load_http_text(source)
|
| 156 |
+
else:
|
| 157 |
+
yield from self._iter_hf_dataset(source)
|
| 158 |
+
|
| 159 |
+
def __iter__(self) -> Iterator[torch.Tensor]:
|
| 160 |
+
buffer: List[int] = []
|
| 161 |
+
for text in self._text_iterator():
|
| 162 |
+
if not text:
|
| 163 |
+
continue
|
| 164 |
+
ids = self.tokenizer.encode(text, add_special_tokens=False).ids
|
| 165 |
+
if self.use_special_tokens:
|
| 166 |
+
bos_id = self.tokenizer.token_to_id("[BOS]")
|
| 167 |
+
eos_id = self.tokenizer.token_to_id("[EOS]")
|
| 168 |
+
if bos_id is not None:
|
| 169 |
+
ids = [bos_id] + ids
|
| 170 |
+
if eos_id is not None:
|
| 171 |
+
ids = ids + [eos_id]
|
| 172 |
+
buffer.extend(ids)
|
| 173 |
+
|
| 174 |
+
while len(buffer) >= self.block_size:
|
| 175 |
+
chunk = torch.tensor(buffer[: self.block_size], dtype=torch.long)
|
| 176 |
+
yield chunk
|
| 177 |
+
buffer = buffer[self.block_size :]
|
| 178 |
+
|
| 179 |
+
if len(buffer) >= self.block_size:
|
| 180 |
+
chunk = torch.tensor(buffer[: self.block_size], dtype=torch.long)
|
| 181 |
+
yield chunk
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def load_streaming_dataset(
|
| 185 |
+
train_source: Union[str, Path],
|
| 186 |
+
tokenizer: Any,
|
| 187 |
+
block_size: int = 512,
|
| 188 |
+
) -> IterableDataset:
|
| 189 |
+
source = Path(train_source) if not isinstance(train_source, Path) else train_source
|
| 190 |
+
if source.suffix == ".pt":
|
| 191 |
+
payload = torch.load(source, map_location="cpu")
|
| 192 |
+
tokens = payload["tokens"] if isinstance(payload, dict) and "tokens" in payload else payload
|
| 193 |
+
return torch.utils.data.TensorDataset(tokens)
|
| 194 |
+
return MarsLMStreamingDataset([source], tokenizer, block_size=block_size)
|
datasets/tiny.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
docs/TerminalGuide.md
CHANGED
|
@@ -26,6 +26,7 @@ Usar scripts listos para entrenar e inferir tu modelo local en Windows.
|
|
| 26 |
- `datasets\preprocess.py` : transforma texto en tensores para entrenamiento.
|
| 27 |
- `inference\generate.py` : bucle autoregresivo de generación.
|
| 28 |
- `quantization\export_gguf.py` : exportación para INT8/INT4/GGUF.
|
|
|
|
| 29 |
- `configs\marslm-100M.yaml`, `configs\marslm-300M.yaml`, `configs\marslm-5B.yaml`, `configs\marslm-10B.yaml` : configuraciones de tamaño y recursos.
|
| 30 |
|
| 31 |
## Cómo mejorar el modelo
|
|
|
|
| 26 |
- `datasets\preprocess.py` : transforma texto en tensores para entrenamiento.
|
| 27 |
- `inference\generate.py` : bucle autoregresivo de generación.
|
| 28 |
- `quantization\export_gguf.py` : exportación para INT8/INT4/GGUF.
|
| 29 |
+
- `scripts\export_llama_cpp.ps1` : helper para exportar y preparar modelos MarsLM para llama.cpp.
|
| 30 |
- `configs\marslm-100M.yaml`, `configs\marslm-300M.yaml`, `configs\marslm-5B.yaml`, `configs\marslm-10B.yaml` : configuraciones de tamaño y recursos.
|
| 31 |
|
| 32 |
## Cómo mejorar el modelo
|
docs/llama_cpp_integration.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ejecución con llama.cpp
|
| 2 |
+
|
| 3 |
+
Este documento describe cómo preparar un modelo MarsLM para ejecutar con llama.cpp.
|
| 4 |
+
|
| 5 |
+
## 1. Requisitos
|
| 6 |
+
- `llama.cpp` compilado en Windows.
|
| 7 |
+
- `python` instalado.
|
| 8 |
+
- Un checkpoint de MarsLM entrenado en `artifacts/checkpoints/marslm-final.pt`.
|
| 9 |
+
- Un tokenizador compatible: `artifacts/tokenizer/marslm.json`.
|
| 10 |
+
|
| 11 |
+
## 2. Exportar a GGUF
|
| 12 |
+
|
| 13 |
+
Si deseas una exportación de metadatos GGUF para integración con llama.cpp / Ollama, usa:
|
| 14 |
+
|
| 15 |
+
```powershell
|
| 16 |
+
python quantization/export_gguf.py --model-path artifacts/checkpoints/marslm-final.pt --config artifacts/checkpoints/config.json --output artifacts/quantized/marslm --quant-type gguf --output-format gguf
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
Esto escribirá un stub GGUF en `artifacts/quantized/marslm.gguf`.
|
| 20 |
+
|
| 21 |
+
## 3. Exportar pesos INT8 / INT4
|
| 22 |
+
|
| 23 |
+
El script también produce payloads cuantizados.
|
| 24 |
+
|
| 25 |
+
INT8:
|
| 26 |
+
```powershell
|
| 27 |
+
python quantization/export_gguf.py --model-path artifacts/checkpoints/marslm-final.pt --config artifacts/checkpoints/config.json --output artifacts/quantized/marslm_int8 --quant-type int8 --output-format pt
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
INT4 (base para Q4/Q5):
|
| 31 |
+
```powershell
|
| 32 |
+
python quantization/export_gguf.py --model-path artifacts/checkpoints/marslm-final.pt --config artifacts/checkpoints/config.json --output artifacts/quantized/marslm_int4 --quant-type int4 --output-format pt
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Q4/Q5 stub:
|
| 36 |
+
```powershell
|
| 37 |
+
python quantization/export_gguf.py --model-path artifacts/checkpoints/marslm-final.pt --config artifacts/checkpoints/config.json --output artifacts/quantized/marslm_q4_1 --quant-type q4_1 --output-format gguf
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
## 4. Uso con llama.cpp
|
| 41 |
+
|
| 42 |
+
Una vez que tengas los pesos cuantizados y el stub GGUF, usa el comando de `llama.cpp` para cargar el modelo.
|
| 43 |
+
|
| 44 |
+
```powershell
|
| 45 |
+
.in
|
| 46 |
+
eleasein ext-generation.exe ^
|
| 47 |
+
--model artifacts\quantized\marslm_q4_1.gguf ^
|
| 48 |
+
--prompt "Hola, escribe un poema corto en español." ^
|
| 49 |
+
--n_predict 128
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
> Nota: esta guía asume que `llama.cpp` puede aceptar el stub GGUF y los pesos en el formato generado. Si `llama.cpp` requiere un conversor adicional, usa `python export/export.py --format gguf` o un conversor de terceros para crear el archivo final compatible.
|
| 53 |
+
|
| 54 |
+
## 5. Observaciones
|
| 55 |
+
- La cuantización INT4 aquí es una aproximación de carga y requiere un convertidor específico si quieres un `.gguf` plenamente compatible.
|
| 56 |
+
- Para peso real Q4/Q5, llama.cpp generalmente usa conversores binarios especializados que ajustan la representación de las matrices.
|
| 57 |
+
- Usa el stub GGUF como base de integración cuando no exista un convertidor directo.
|
evaluation/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .metrics import compute_perplexity, compute_tokens_per_second
|
| 2 |
+
from .evaluate import evaluate_model
|
| 3 |
+
|
| 4 |
+
__all__ = ["compute_perplexity", "compute_tokens_per_second", "evaluate_model"]
|
evaluation/__pycache__/evaluate.cpython-314.pyc
ADDED
|
Binary file (7.13 kB). View file
|
|
|
evaluation/__pycache__/metrics.cpython-314.pyc
ADDED
|
Binary file (3.27 kB). View file
|
|
|
evaluation/evaluate.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from time import perf_counter
|
| 4 |
+
from typing import Dict, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils.data import DataLoader
|
| 8 |
+
|
| 9 |
+
from model.transformer import MarsLMConfig, MarsLMForCausalLM, align_state_dict_keys
|
| 10 |
+
from tokenizer.tokenizer_utils import load_tokenizer
|
| 11 |
+
from evaluation.metrics import compute_loss, compute_perplexity, compute_tokens_per_second
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_model(model_path: Path, config_path: Path, device: torch.device) -> MarsLMForCausalLM:
|
| 15 |
+
raw_config = json.loads(config_path.read_text(encoding="utf-8"))
|
| 16 |
+
config = MarsLMConfig.from_dict({"model": raw_config})
|
| 17 |
+
model = MarsLMForCausalLM(config).to(device)
|
| 18 |
+
state = torch.load(model_path, map_location=device)
|
| 19 |
+
if isinstance(state, dict) and "model_state" in state:
|
| 20 |
+
state = state["model_state"]
|
| 21 |
+
state = align_state_dict_keys(state)
|
| 22 |
+
model.load_state_dict(state, strict=False)
|
| 23 |
+
model.eval()
|
| 24 |
+
return model
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def evaluate_model(
|
| 28 |
+
model_path: str,
|
| 29 |
+
config_path: str,
|
| 30 |
+
tokenizer_path: str,
|
| 31 |
+
eval_path: str,
|
| 32 |
+
batch_size: int = 1,
|
| 33 |
+
block_size: int = 512,
|
| 34 |
+
device: Optional[str] = None,
|
| 35 |
+
) -> Dict[str, float]:
|
| 36 |
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 37 |
+
device = torch.device(device)
|
| 38 |
+
tokenizer = load_tokenizer(Path(tokenizer_path))
|
| 39 |
+
model = load_model(Path(model_path), Path(config_path), device)
|
| 40 |
+
|
| 41 |
+
texts = []
|
| 42 |
+
eval_file = Path(eval_path)
|
| 43 |
+
if eval_file.suffix == ".jsonl":
|
| 44 |
+
with eval_file.open("r", encoding="utf-8") as handle:
|
| 45 |
+
for line in handle:
|
| 46 |
+
if not line.strip():
|
| 47 |
+
continue
|
| 48 |
+
texts.append(json.loads(line).get("text", ""))
|
| 49 |
+
else:
|
| 50 |
+
with eval_file.open("r", encoding="utf-8") as handle:
|
| 51 |
+
texts = [line.strip() for line in handle if line.strip()]
|
| 52 |
+
|
| 53 |
+
inputs = [torch.tensor(tokenizer.encode(text, add_special_tokens=False).ids, dtype=torch.long) for text in texts if text]
|
| 54 |
+
inputs = [i for i in inputs if i.numel() >= 2]
|
| 55 |
+
if not inputs:
|
| 56 |
+
raise ValueError("No valid evaluation examples were found.")
|
| 57 |
+
|
| 58 |
+
batches = []
|
| 59 |
+
for i in range(0, len(inputs), batch_size):
|
| 60 |
+
batch = inputs[i : i + batch_size]
|
| 61 |
+
length = min(min(x.numel() for x in batch), block_size)
|
| 62 |
+
padded = torch.stack([x[:length] for x in batch])
|
| 63 |
+
batches.append(padded)
|
| 64 |
+
|
| 65 |
+
total_loss = 0.0
|
| 66 |
+
total_tokens = 0
|
| 67 |
+
start = perf_counter()
|
| 68 |
+
with torch.no_grad():
|
| 69 |
+
for batch in batches:
|
| 70 |
+
batch = batch.to(device)
|
| 71 |
+
logits, _ = model(batch)
|
| 72 |
+
loss_value, num_tokens = compute_loss(logits, batch)
|
| 73 |
+
total_loss += loss_value * num_tokens
|
| 74 |
+
total_tokens += num_tokens
|
| 75 |
+
elapsed = perf_counter() - start
|
| 76 |
+
|
| 77 |
+
avg_loss = total_loss / max(total_tokens, 1)
|
| 78 |
+
perplexity = compute_perplexity(avg_loss)
|
| 79 |
+
throughput = compute_tokens_per_second(total_tokens, elapsed)
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"loss": avg_loss,
|
| 83 |
+
"perplexity": perplexity,
|
| 84 |
+
"tokens": float(total_tokens),
|
| 85 |
+
"tokens_per_second": throughput,
|
| 86 |
+
"elapsed_seconds": elapsed,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
import argparse
|
| 92 |
+
|
| 93 |
+
parser = argparse.ArgumentParser(description="Evaluate a MarsLM checkpoint")
|
| 94 |
+
parser.add_argument("--model-path", required=True)
|
| 95 |
+
parser.add_argument("--config", required=True)
|
| 96 |
+
parser.add_argument("--tokenizer-model", required=True)
|
| 97 |
+
parser.add_argument("--eval-file", required=True)
|
| 98 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
| 99 |
+
parser.add_argument("--block-size", type=int, default=512)
|
| 100 |
+
parser.add_argument("--device", default=None)
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
|
| 103 |
+
metrics = evaluate_model(
|
| 104 |
+
args.model_path,
|
| 105 |
+
args.config,
|
| 106 |
+
args.tokenizer_model,
|
| 107 |
+
args.eval_file,
|
| 108 |
+
batch_size=args.batch_size,
|
| 109 |
+
block_size=args.block_size,
|
| 110 |
+
device=args.device,
|
| 111 |
+
)
|
| 112 |
+
print(json.dumps(metrics, indent=2))
|
evaluation/metrics.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from time import perf_counter
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def compute_perplexity(loss: float) -> float:
|
| 9 |
+
return math.exp(loss)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def compute_tokens_per_second(num_tokens: int, elapsed_seconds: float) -> float:
|
| 13 |
+
return num_tokens / max(elapsed_seconds, 1e-9)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def compute_loss(logits: torch.Tensor, labels: torch.Tensor) -> Tuple[float, int]:
|
| 17 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 18 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 19 |
+
loss = torch.nn.functional.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), reduction="mean")
|
| 20 |
+
return loss.item(), shift_labels.numel()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def measure_inference_speed(model: torch.nn.Module, input_ids: torch.Tensor, warmup_runs: int = 5) -> Tuple[float, float]:
|
| 24 |
+
device = next(model.parameters()).device
|
| 25 |
+
input_ids = input_ids.to(device)
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
for _ in range(warmup_runs):
|
| 28 |
+
model(input_ids)
|
| 29 |
+
start = perf_counter()
|
| 30 |
+
logits, _ = model(input_ids)
|
| 31 |
+
end = perf_counter()
|
| 32 |
+
elapsed = end - start
|
| 33 |
+
return elapsed, input_ids.numel()
|
export/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .export import export_checkpoint
|
| 2 |
+
|
| 3 |
+
__all__ = ["export_checkpoint"]
|
export/__pycache__/export.cpython-314.pyc
ADDED
|
Binary file (4.64 kB). View file
|
|
|
export/export.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import safetensors.torch as safetensors
|
| 9 |
+
except ImportError: # type: ignore
|
| 10 |
+
safetensors = None # type: ignore
|
| 11 |
+
|
| 12 |
+
from model.transformer import MarsLMConfig, MarsLMForCausalLM, align_state_dict_keys
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def load_model(model_path: Path, config_path: Path, device: torch.device) -> MarsLMForCausalLM:
|
| 16 |
+
raw_config = json.loads(config_path.read_text(encoding="utf-8"))
|
| 17 |
+
config = MarsLMConfig.from_dict({"model": raw_config})
|
| 18 |
+
model = MarsLMForCausalLM(config).to(device)
|
| 19 |
+
state = torch.load(model_path, map_location=device)
|
| 20 |
+
if isinstance(state, dict) and "model_state" in state:
|
| 21 |
+
state = state["model_state"]
|
| 22 |
+
state = align_state_dict_keys(state)
|
| 23 |
+
model.load_state_dict(state, strict=False)
|
| 24 |
+
return model
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def export_checkpoint(
|
| 28 |
+
model_path: str,
|
| 29 |
+
config_path: str,
|
| 30 |
+
output_path: str,
|
| 31 |
+
format: str = "pt",
|
| 32 |
+
device: str = "cpu",
|
| 33 |
+
use_safetensors: bool = False,
|
| 34 |
+
) -> str:
|
| 35 |
+
model = load_model(Path(model_path), Path(config_path), torch.device(device))
|
| 36 |
+
output_path = Path(output_path)
|
| 37 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
|
| 39 |
+
if format == "pt":
|
| 40 |
+
torch.save(model.state_dict(), output_path)
|
| 41 |
+
elif format == "safetensors":
|
| 42 |
+
if safetensors is None:
|
| 43 |
+
raise RuntimeError("safetensors is not installed")
|
| 44 |
+
state_dict = model.state_dict()
|
| 45 |
+
safetensors.save_file({k: v.cpu() for k, v in state_dict.items()}, str(output_path))
|
| 46 |
+
elif format == "gguf":
|
| 47 |
+
metadata = {
|
| 48 |
+
"format": "gguf",
|
| 49 |
+
"model": {
|
| 50 |
+
"vocab_size": model.config.vocab_size,
|
| 51 |
+
"hidden_size": model.config.hidden_size,
|
| 52 |
+
"num_hidden_layers": model.config.num_hidden_layers,
|
| 53 |
+
"num_attention_heads": model.config.num_attention_heads,
|
| 54 |
+
},
|
| 55 |
+
}
|
| 56 |
+
output_path.write_text(json.dumps(metadata, indent=2), encoding="utf-8")
|
| 57 |
+
else:
|
| 58 |
+
raise ValueError(f"Unsupported export format: {format}")
|
| 59 |
+
|
| 60 |
+
return str(output_path)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
import argparse
|
| 65 |
+
|
| 66 |
+
parser = argparse.ArgumentParser(description="Export a MarsLM checkpoint")
|
| 67 |
+
parser.add_argument("--model-path", required=True)
|
| 68 |
+
parser.add_argument("--config", required=True)
|
| 69 |
+
parser.add_argument("--output-path", required=True)
|
| 70 |
+
parser.add_argument("--format", choices=["pt", "safetensors", "gguf"], default="pt")
|
| 71 |
+
parser.add_argument("--device", default="cpu")
|
| 72 |
+
args = parser.parse_args()
|
| 73 |
+
result = export_checkpoint(args.model_path, args.config, args.output_path, format=args.format, device=args.device)
|
| 74 |
+
print(f"Exported checkpoint to {result}")
|
requirements.txt
CHANGED
|
@@ -4,4 +4,5 @@ datasets
|
|
| 4 |
accelerate
|
| 5 |
huggingface_hub
|
| 6 |
tqdm
|
| 7 |
-
pyyaml
|
|
|
|
|
|
| 4 |
accelerate
|
| 5 |
huggingface_hub
|
| 6 |
tqdm
|
| 7 |
+
pyyaml
|
| 8 |
+
safetensors
|
scripts/chat_model.ps1
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PowerShell helper para cargar el modelo y abrir un prompt interactivo.
|
| 2 |
+
# Ejecuta este script desde el directorio MarsLM.
|
| 3 |
+
|
| 4 |
+
param(
|
| 5 |
+
[string]$ModelPath = "artifacts\checkpoints\marslm-final.pt",
|
| 6 |
+
[string]$ConfigPath = "artifacts\checkpoints\config.json",
|
| 7 |
+
[string]$TokenizerPath = "artifacts\tokenizer\marslm.json",
|
| 8 |
+
[int]$MaxNewTokens = 128,
|
| 9 |
+
[double]$Temperature = 0.8,
|
| 10 |
+
[int]$TopK = 50,
|
| 11 |
+
[double]$TopP = 0.0,
|
| 12 |
+
[double]$RepetitionPenalty = 1.0
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
| 16 |
+
Set-Location "$root\.."
|
| 17 |
+
|
| 18 |
+
Write-Host "Iniciando MarsLM en modo interactivo..."
|
| 19 |
+
python inference/generate.py --model-path $ModelPath --config $ConfigPath --tokenizer-model $TokenizerPath --interactive --max-new-tokens $MaxNewTokens --temperature $Temperature --top-k $TopK --top-p $TopP --repetition-penalty $RepetitionPenalty
|
scripts/export_llama_cpp.ps1
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<#
|
| 2 |
+
PowerShell helper para generar los artefactos de MarsLM que luego puede intentar cargar llama.cpp.
|
| 3 |
+
#>
|
| 4 |
+
|
| 5 |
+
param(
|
| 6 |
+
[string]$ModelPath = "artifacts\checkpoints\marslm-final.pt",
|
| 7 |
+
[string]$ConfigPath = "artifacts\checkpoints\config.json",
|
| 8 |
+
[string]$OutputPrefix = "artifacts\quantized\marslm_q4_1"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
| 12 |
+
Set-Location "$root\.."
|
| 13 |
+
|
| 14 |
+
Write-Host "Exportando artesfactos para llama.cpp..."
|
| 15 |
+
|
| 16 |
+
python quantization/export_gguf.py --model-path $ModelPath --config $ConfigPath --output $OutputPrefix --quant-type q4_1 --output-format gguf
|
| 17 |
+
|
| 18 |
+
Write-Host "Listo. Archivos generados:"
|
| 19 |
+
Write-Host " $OutputPrefix.gguf"
|
| 20 |
+
Write-Host " $OutputPrefix.safetensors (o .pt si safetensors no está disponible)"
|
scripts/generate_yaml.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import yaml
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def estimate_params(hidden, layers, vocab, intermediate):
|
| 9 |
+
embeddings = vocab * hidden
|
| 10 |
+
transformer = layers * (
|
| 11 |
+
4 * hidden * hidden +
|
| 12 |
+
2 * hidden * intermediate
|
| 13 |
+
)
|
| 14 |
+
return embeddings + transformer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def round_multiple(value, multiple=64):
|
| 18 |
+
return int(math.ceil(value / multiple) * multiple)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def generate_config(target_params):
|
| 22 |
+
vocab = 32000
|
| 23 |
+
|
| 24 |
+
if target_params <= 500_000_000:
|
| 25 |
+
hidden = 1280
|
| 26 |
+
layers = 20
|
| 27 |
+
elif target_params <= 700_000_000:
|
| 28 |
+
hidden = 1536
|
| 29 |
+
layers = 24
|
| 30 |
+
elif target_params <= 1_000_000_000:
|
| 31 |
+
hidden = 2048
|
| 32 |
+
layers = 24
|
| 33 |
+
else:
|
| 34 |
+
hidden = 2560
|
| 35 |
+
layers = 28
|
| 36 |
+
|
| 37 |
+
intermediate = round_multiple(hidden * 4)
|
| 38 |
+
|
| 39 |
+
while estimate_params(hidden, layers, vocab, intermediate) < target_params:
|
| 40 |
+
hidden += 64
|
| 41 |
+
intermediate = round_multiple(hidden * 4)
|
| 42 |
+
|
| 43 |
+
heads = hidden // 128
|
| 44 |
+
|
| 45 |
+
config = {
|
| 46 |
+
"model": {
|
| 47 |
+
"vocab_size": vocab,
|
| 48 |
+
"hidden_size": hidden,
|
| 49 |
+
"intermediate_size": intermediate,
|
| 50 |
+
"num_hidden_layers": layers,
|
| 51 |
+
"num_attention_heads": heads,
|
| 52 |
+
"max_position_embeddings": 4096,
|
| 53 |
+
"dropout": 0.0,
|
| 54 |
+
"rope_theta": 10000.0,
|
| 55 |
+
},
|
| 56 |
+
"training": {
|
| 57 |
+
"epochs": 10,
|
| 58 |
+
"batch_size": 1,
|
| 59 |
+
"learning_rate": 1e-4,
|
| 60 |
+
"weight_decay": 0.01,
|
| 61 |
+
"block_size": 512,
|
| 62 |
+
"checkpoint_interval": 100,
|
| 63 |
+
"gradient_accumulation_steps": 32,
|
| 64 |
+
"warmup_steps": 1000,
|
| 65 |
+
},
|
| 66 |
+
"system": {
|
| 67 |
+
"device": "auto",
|
| 68 |
+
"torch_threads": 4,
|
| 69 |
+
},
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return config, estimate_params(hidden, layers, vocab, intermediate)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def main():
|
| 76 |
+
parser = argparse.ArgumentParser()
|
| 77 |
+
parser.add_argument(
|
| 78 |
+
"--params",
|
| 79 |
+
type=float,
|
| 80 |
+
default=1.0,
|
| 81 |
+
help="Objetivo en miles de millones (ej: 1.0 = 1B)",
|
| 82 |
+
)
|
| 83 |
+
parser.add_argument(
|
| 84 |
+
"--output",
|
| 85 |
+
default="configs/marslm-auto.yaml",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
|
| 90 |
+
target = int(args.params * 1_000_000_000)
|
| 91 |
+
|
| 92 |
+
config, estimated = generate_config(target)
|
| 93 |
+
|
| 94 |
+
output = Path(args.output)
|
| 95 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
|
| 97 |
+
with output.open("w", encoding="utf-8") as f:
|
| 98 |
+
yaml.safe_dump(config, f, sort_keys=False)
|
| 99 |
+
|
| 100 |
+
print(f"Archivo generado: {output}")
|
| 101 |
+
print(f"Parámetros aproximados: {estimated:,}")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
main()
|
tests/__pycache__/test_inference_cases.cpython-314.pyc
ADDED
|
Binary file (3.18 kB). View file
|
|
|
tests/test_inference_cases.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from inference.generate import generate, load_model
|
| 8 |
+
from tokenizer.tokenizer_utils import load_tokenizer
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 11 |
+
DEFAULT_MODEL_PATH = ROOT / "artifacts" / "checkpoints" / "marslm-final.pt"
|
| 12 |
+
DEFAULT_CONFIG_PATH = ROOT / "artifacts" / "checkpoints" / "config.json"
|
| 13 |
+
DEFAULT_TOKENIZER_PATH = ROOT / "artifacts" / "tokenizer" / "marslm.json"
|
| 14 |
+
|
| 15 |
+
CATEGORY_PROMPTS = {
|
| 16 |
+
"comprension_lectora": [
|
| 17 |
+
"Lee el siguiente texto y responde: ¿Cuál es el tema principal? 'La inteligencia artificial está cambiando la forma en que trabajamos y aprendemos.'",
|
| 18 |
+
],
|
| 19 |
+
"matematicas": [
|
| 20 |
+
"Resuelve el siguiente problema: ¿Cuánto es 7 más 8?"],
|
| 21 |
+
"codigo": [
|
| 22 |
+
"Escribe un fragmento de Python que invierta una lista y lo explique brevemente."],
|
| 23 |
+
"espanol": [
|
| 24 |
+
"Completa la oración en español: 'El perro corre rápido porque...'"],
|
| 25 |
+
"conocimientos_generales": [
|
| 26 |
+
"¿Quién fue el primer presidente de los Estados Unidos?"],
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture(scope="session")
|
| 31 |
+
def model_and_tokenizer():
|
| 32 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 33 |
+
tokenizer = load_tokenizer(DEFAULT_TOKENIZER_PATH)
|
| 34 |
+
model = load_model(DEFAULT_MODEL_PATH, DEFAULT_CONFIG_PATH, device)
|
| 35 |
+
return model, tokenizer
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@pytest.mark.parametrize("category,prompts", CATEGORY_PROMPTS.items())
|
| 39 |
+
def test_generation_for_category(model_and_tokenizer, category, prompts):
|
| 40 |
+
model, tokenizer = model_and_tokenizer
|
| 41 |
+
for prompt in prompts:
|
| 42 |
+
outputs = list(
|
| 43 |
+
generate(
|
| 44 |
+
model,
|
| 45 |
+
tokenizer,
|
| 46 |
+
prompt,
|
| 47 |
+
max_new_tokens=64,
|
| 48 |
+
temperature=0.7,
|
| 49 |
+
top_k=40,
|
| 50 |
+
top_p=0.9,
|
| 51 |
+
repetition_penalty=1.1,
|
| 52 |
+
stream=False,
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
assert outputs, f"No se generó texto para la categoría {category}"
|
| 56 |
+
assert isinstance(outputs[0], str)
|
| 57 |
+
assert len(outputs[0].strip()) > 0
|
| 58 |
+
assert outputs[0].strip().lower() != prompt.strip().lower()
|
training/__pycache__/instruction_train.cpython-314.pyc
ADDED
|
Binary file (13 kB). View file
|
|
|
training/__pycache__/train.cpython-314.pyc
CHANGED
|
Binary files a/training/__pycache__/train.cpython-314.pyc and b/training/__pycache__/train.cpython-314.pyc differ
|
|
|
training/instruction_train.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import yaml
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.cuda.amp import autocast, GradScaler
|
| 13 |
+
from torch.utils.data import DataLoader
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
if str(ROOT) not in sys.path:
|
| 17 |
+
sys.path.append(str(ROOT))
|
| 18 |
+
|
| 19 |
+
from datasets.instruction import InstructionTuningDataset
|
| 20 |
+
from model.transformer import MarsLMConfig, MarsLMForCausalLM
|
| 21 |
+
from tokenizer.tokenizer_utils import load_tokenizer
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_config(path: Path):
|
| 25 |
+
with path.open("r", encoding="utf-8") as handle:
|
| 26 |
+
raw = yaml.safe_load(handle)
|
| 27 |
+
config = MarsLMConfig.from_dict(raw)
|
| 28 |
+
config.extra["training"] = raw.get("training", {})
|
| 29 |
+
config.extra["system"] = raw.get("system", {})
|
| 30 |
+
return config, raw
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save_checkpoint(path: Path, model: nn.Module, optimizer, scheduler, epoch: int, step: int, config: MarsLMConfig):
|
| 34 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
torch.save(
|
| 36 |
+
{
|
| 37 |
+
"model_state": model.state_dict(),
|
| 38 |
+
"optimizer_state": optimizer.state_dict(),
|
| 39 |
+
"scheduler_state": scheduler.state_dict(),
|
| 40 |
+
"epoch": epoch,
|
| 41 |
+
"step": step,
|
| 42 |
+
"config": config.__dict__,
|
| 43 |
+
},
|
| 44 |
+
path,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_checkpoint(path: Path, model: nn.Module, optimizer, scheduler):
|
| 49 |
+
payload = torch.load(path, map_location="cpu")
|
| 50 |
+
model.load_state_dict(payload["model_state"])
|
| 51 |
+
optimizer.load_state_dict(payload["optimizer_state"])
|
| 52 |
+
scheduler.load_state_dict(payload["scheduler_state"])
|
| 53 |
+
return payload["epoch"], payload["step"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
parser = argparse.ArgumentParser(description="Instruction-tune a MarsLM model")
|
| 58 |
+
parser.add_argument("--config", default=str(ROOT / "configs" / "marslm-700M-v2.yaml"))
|
| 59 |
+
parser.add_argument("--train-file", required=True, help="JSONL or Hugging Face dataset identifier")
|
| 60 |
+
parser.add_argument("--tokenizer-model", required=True)
|
| 61 |
+
parser.add_argument("--output-dir", default=str(ROOT / "artifacts" / "checkpoints"))
|
| 62 |
+
parser.add_argument("--epochs", type=int, default=None)
|
| 63 |
+
parser.add_argument("--batch-size", type=int, default=None)
|
| 64 |
+
parser.add_argument("--learning-rate", type=float, default=None)
|
| 65 |
+
parser.add_argument("--weight-decay", type=float, default=None)
|
| 66 |
+
parser.add_argument("--block-size", type=int, default=None)
|
| 67 |
+
parser.add_argument("--checkpoint-interval", type=int, default=None)
|
| 68 |
+
parser.add_argument("--gradient-accumulation-steps", type=int, default=None)
|
| 69 |
+
parser.add_argument("--warmup-steps", type=int, default=None)
|
| 70 |
+
parser.add_argument("--max-steps", type=int, default=None)
|
| 71 |
+
parser.add_argument("--resume", default=None)
|
| 72 |
+
parser.add_argument("--use-fp16", type=lambda x: bool(int(x)), default=None)
|
| 73 |
+
parser.add_argument("--gradient-checkpointing", action="store_true")
|
| 74 |
+
parser.add_argument("--prompt-template", default="### Instruction:\n{instruction}\n\n### Response:\n{response}")
|
| 75 |
+
args = parser.parse_args()
|
| 76 |
+
|
| 77 |
+
config_path = Path(args.config).resolve()
|
| 78 |
+
config, raw = load_config(config_path)
|
| 79 |
+
train_source = args.train_file
|
| 80 |
+
tokenizer = load_tokenizer(Path(args.tokenizer_model).resolve())
|
| 81 |
+
output_dir = Path(args.output_dir).resolve()
|
| 82 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
|
| 84 |
+
training_cfg = raw.get("training", {})
|
| 85 |
+
system_cfg = raw.get("system", {})
|
| 86 |
+
|
| 87 |
+
args.epochs = args.epochs if args.epochs is not None else int(training_cfg.get("epochs", 1))
|
| 88 |
+
args.batch_size = args.batch_size if args.batch_size is not None else int(training_cfg.get("batch_size", 1))
|
| 89 |
+
args.learning_rate = args.learning_rate if args.learning_rate is not None else float(training_cfg.get("learning_rate", 2e-5))
|
| 90 |
+
args.weight_decay = args.weight_decay if args.weight_decay is not None else float(training_cfg.get("weight_decay", 0.0))
|
| 91 |
+
args.block_size = args.block_size if args.block_size is not None else int(training_cfg.get("block_size", 1024))
|
| 92 |
+
args.checkpoint_interval = args.checkpoint_interval if args.checkpoint_interval is not None else int(training_cfg.get("checkpoint_interval", 100))
|
| 93 |
+
args.gradient_accumulation_steps = args.gradient_accumulation_steps if args.gradient_accumulation_steps is not None else int(training_cfg.get("gradient_accumulation_steps", 1))
|
| 94 |
+
args.warmup_steps = args.warmup_steps if args.warmup_steps is not None else int(training_cfg.get("warmup_steps", 50))
|
| 95 |
+
args.max_steps = args.max_steps if args.max_steps is not None else int(training_cfg.get("max_steps", 0))
|
| 96 |
+
args.use_fp16 = args.use_fp16 if args.use_fp16 is not None else bool(training_cfg.get("use_fp16", False))
|
| 97 |
+
|
| 98 |
+
requested_device = system_cfg.get("device", "auto")
|
| 99 |
+
if requested_device in {"auto", "cuda", "gpu"} and torch.cuda.is_available():
|
| 100 |
+
device = torch.device("cuda")
|
| 101 |
+
elif requested_device in {"auto", "cuda", "gpu"}:
|
| 102 |
+
device = torch.device("cpu")
|
| 103 |
+
else:
|
| 104 |
+
device = torch.device(requested_device)
|
| 105 |
+
|
| 106 |
+
torch.set_num_threads(int(system_cfg.get("torch_threads", 4)))
|
| 107 |
+
print(f"Using device: {device}")
|
| 108 |
+
|
| 109 |
+
config.gradient_checkpointing = args.gradient_checkpointing
|
| 110 |
+
dataset = InstructionTuningDataset([train_source], tokenizer, block_size=args.block_size, prompt_template=args.prompt_template)
|
| 111 |
+
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, num_workers=0)
|
| 112 |
+
|
| 113 |
+
model = MarsLMForCausalLM(config).to(device)
|
| 114 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 115 |
+
scaler = GradScaler() if args.use_fp16 and device.type == "cuda" else None
|
| 116 |
+
|
| 117 |
+
start_epoch = 0
|
| 118 |
+
step = 0
|
| 119 |
+
if args.resume is not None:
|
| 120 |
+
start_epoch, step = load_checkpoint(Path(args.resume).resolve(), model, optimizer, None)
|
| 121 |
+
print(f"Resumed from {args.resume}")
|
| 122 |
+
|
| 123 |
+
model.train()
|
| 124 |
+
optimizer.zero_grad(set_to_none=True)
|
| 125 |
+
for epoch in range(start_epoch, args.epochs):
|
| 126 |
+
for batch_idx, batch_tokens in enumerate(loader):
|
| 127 |
+
if isinstance(batch_tokens, (list, tuple)):
|
| 128 |
+
batch_tokens = batch_tokens[0]
|
| 129 |
+
batch_tokens = batch_tokens.to(device)
|
| 130 |
+
|
| 131 |
+
with autocast(enabled=scaler is not None):
|
| 132 |
+
logits, _ = model(batch_tokens)
|
| 133 |
+
shift_logits = logits[:, :-1, :].contiguous().view(-1, config.vocab_size)
|
| 134 |
+
shift_labels = batch_tokens[:, 1:].contiguous().view(-1)
|
| 135 |
+
loss = F.cross_entropy(shift_logits, shift_labels)
|
| 136 |
+
|
| 137 |
+
if scaler is not None:
|
| 138 |
+
scaler.scale(loss).backward()
|
| 139 |
+
scaler.unscale_(optimizer)
|
| 140 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 141 |
+
scaler.step(optimizer)
|
| 142 |
+
scaler.update()
|
| 143 |
+
else:
|
| 144 |
+
loss.backward()
|
| 145 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 146 |
+
optimizer.step()
|
| 147 |
+
|
| 148 |
+
optimizer.zero_grad(set_to_none=True)
|
| 149 |
+
step += 1
|
| 150 |
+
|
| 151 |
+
if args.checkpoint_interval and step % args.checkpoint_interval == 0:
|
| 152 |
+
output_path = output_dir / f"instruction-checkpoint-step{step:06d}.pt"
|
| 153 |
+
save_checkpoint(output_path, model, optimizer, None, epoch + 1, step, config)
|
| 154 |
+
print(f"Saved instruction tuning checkpoint {output_path}")
|
| 155 |
+
|
| 156 |
+
if args.max_steps and step >= args.max_steps:
|
| 157 |
+
break
|
| 158 |
+
if args.max_steps and step >= args.max_steps:
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
final_path = output_dir / "marslm-700M-chat-final.pt"
|
| 162 |
+
torch.save(model.state_dict(), final_path)
|
| 163 |
+
print(f"Saved final chat-tuned model to {final_path}")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
training/train.py
CHANGED
|
@@ -9,12 +9,14 @@ import torch
|
|
| 9 |
import torch.nn.functional as F
|
| 10 |
import yaml
|
| 11 |
from torch import nn
|
| 12 |
-
from torch.
|
|
|
|
| 13 |
|
| 14 |
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
if str(ROOT) not in sys.path:
|
| 16 |
-
sys.path.
|
| 17 |
|
|
|
|
| 18 |
from model.transformer import MarsLMConfig, MarsLMForCausalLM
|
| 19 |
from tokenizer.tokenizer_utils import load_tokenizer, encode_text
|
| 20 |
|
|
@@ -22,21 +24,9 @@ from tokenizer.tokenizer_utils import load_tokenizer, encode_text
|
|
| 22 |
def load_config(path: Path):
|
| 23 |
with path.open("r", encoding="utf-8") as handle:
|
| 24 |
raw = yaml.safe_load(handle)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
config = MarsLMConfig(
|
| 29 |
-
vocab_size=int(model_cfg.get("vocab_size", 32000)),
|
| 30 |
-
hidden_size=int(model_cfg.get("hidden_size", 768)),
|
| 31 |
-
intermediate_size=int(model_cfg.get("intermediate_size", 2048)),
|
| 32 |
-
num_hidden_layers=int(model_cfg.get("num_hidden_layers", 12)),
|
| 33 |
-
num_attention_heads=int(model_cfg.get("num_attention_heads", 12)),
|
| 34 |
-
max_position_embeddings=int(model_cfg.get("max_position_embeddings", 2048)),
|
| 35 |
-
dropout=float(model_cfg.get("dropout", 0.0)),
|
| 36 |
-
rope_theta=float(model_cfg.get("rope_theta", 10000.0)),
|
| 37 |
-
)
|
| 38 |
-
config.training = training_cfg
|
| 39 |
-
config.system = system_cfg
|
| 40 |
return config, raw
|
| 41 |
|
| 42 |
|
|
@@ -45,11 +35,21 @@ def load_training_tokens(train_path: Path, tokenizer_path: Path, block_size: int
|
|
| 45 |
if train_path.suffix == ".pt":
|
| 46 |
payload = torch.load(train_path, map_location="cpu")
|
| 47 |
tokens = payload["tokens"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
else:
|
| 49 |
text = train_path.read_text(encoding="utf-8")
|
| 50 |
-
ids = encode_text(tokenizer, text)
|
| 51 |
-
tokens = torch.tensor(ids, dtype=torch.long)
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
|
| 55 |
def save_checkpoint(path: Path, model: nn.Module, optimizer, scheduler, epoch: int, step: int, config: MarsLMConfig):
|
|
@@ -75,6 +75,25 @@ def load_checkpoint(path: Path, model: nn.Module, optimizer, scheduler):
|
|
| 75 |
return payload["epoch"], payload["step"]
|
| 76 |
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def main():
|
| 79 |
parser = argparse.ArgumentParser(description="Train a MarsLM model")
|
| 80 |
parser.add_argument("--config", default=str(ROOT / "configs" / "marslm-100M.yaml"))
|
|
@@ -90,12 +109,19 @@ def main():
|
|
| 90 |
parser.add_argument("--gradient-accumulation-steps", type=int, default=None)
|
| 91 |
parser.add_argument("--warmup-steps", type=int, default=None)
|
| 92 |
parser.add_argument("--max-steps", type=int, default=None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
parser.add_argument("--resume", default=None)
|
| 94 |
args = parser.parse_args()
|
| 95 |
|
| 96 |
config_path = Path(args.config).resolve()
|
| 97 |
config, raw = load_config(config_path)
|
| 98 |
-
|
|
|
|
|
|
|
| 99 |
tokenizer_path = Path(args.tokenizer_model).resolve()
|
| 100 |
output_dir = Path(args.output_dir).resolve()
|
| 101 |
output_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -111,6 +137,9 @@ def main():
|
|
| 111 |
args.checkpoint_interval = args.checkpoint_interval if args.checkpoint_interval is not None else int(training_cfg.get("checkpoint_interval", 200))
|
| 112 |
args.gradient_accumulation_steps = args.gradient_accumulation_steps if args.gradient_accumulation_steps is not None else int(training_cfg.get("gradient_accumulation_steps", 1))
|
| 113 |
args.warmup_steps = args.warmup_steps if args.warmup_steps is not None else int(training_cfg.get("warmup_steps", 50))
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
requested_device = system_cfg.get("device", "auto")
|
| 116 |
if requested_device in {"auto", "cuda", "gpu"} and torch.cuda.is_available():
|
|
@@ -123,18 +152,29 @@ def main():
|
|
| 123 |
torch.set_num_threads(int(system_cfg.get("torch_threads", 4)))
|
| 124 |
print(f"Using device: {device}")
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
model = MarsLMForCausalLM(config).to(device)
|
| 131 |
optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 132 |
grad_accum_steps = max(1, args.gradient_accumulation_steps)
|
| 133 |
-
max_steps = args.max_steps
|
| 134 |
|
| 135 |
def lr_lambda(step):
|
| 136 |
if step < args.warmup_steps:
|
| 137 |
return (step + 1) / max(1, args.warmup_steps)
|
|
|
|
|
|
|
| 138 |
if step >= max_steps:
|
| 139 |
return 0.0
|
| 140 |
progress = (step - args.warmup_steps) / max(1, max_steps - args.warmup_steps)
|
|
@@ -148,51 +188,69 @@ def main():
|
|
| 148 |
start_epoch, step = load_checkpoint(Path(args.resume).resolve(), model, optimizer, scheduler)
|
| 149 |
print(f"Resumed from {args.resume}")
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
model.train()
|
| 152 |
optimizer.zero_grad(set_to_none=True)
|
| 153 |
for epoch in range(start_epoch, args.epochs):
|
| 154 |
-
for batch_idx,
|
|
|
|
|
|
|
| 155 |
batch_tokens = batch_tokens.to(device)
|
| 156 |
-
logits, _ = model(batch_tokens)
|
| 157 |
-
shift_logits = logits[:, :-1, :].contiguous().view(-1, config.vocab_size)
|
| 158 |
-
shift_labels = batch_tokens[:, 1:].contiguous().view(-1)
|
| 159 |
-
loss = F.cross_entropy(shift_logits, shift_labels) / grad_accum_steps
|
| 160 |
-
loss.backward()
|
| 161 |
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
optimizer.zero_grad(set_to_none=True)
|
| 166 |
scheduler.step()
|
| 167 |
step += 1
|
| 168 |
|
| 169 |
-
if step % args.checkpoint_interval == 0
|
| 170 |
checkpoint_path = output_dir / f"checkpoint-epoch{epoch + 1:02d}-step{step:06d}.pt"
|
| 171 |
save_checkpoint(checkpoint_path, model, optimizer, scheduler, epoch + 1, step, config)
|
|
|
|
| 172 |
print(f"Saved checkpoint {checkpoint_path} with loss {loss.item():.4f}")
|
| 173 |
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
break
|
| 176 |
|
| 177 |
-
if step >= max_steps:
|
| 178 |
break
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
|
|
|
| 182 |
|
| 183 |
final_path = output_dir / "marslm-final.pt"
|
| 184 |
torch.save(model.state_dict(), final_path)
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
"num_hidden_layers": config.num_hidden_layers,
|
| 190 |
-
"num_attention_heads": config.num_attention_heads,
|
| 191 |
-
"max_position_embeddings": config.max_position_embeddings,
|
| 192 |
-
"dropout": config.dropout,
|
| 193 |
-
"rope_theta": config.rope_theta,
|
| 194 |
-
}
|
| 195 |
-
(output_dir / "config.json").write_text(json.dumps(config_payload, indent=2), encoding="utf-8")
|
| 196 |
print(f"Training complete. Final weights saved to {final_path}")
|
| 197 |
|
| 198 |
|
|
|
|
| 9 |
import torch.nn.functional as F
|
| 10 |
import yaml
|
| 11 |
from torch import nn
|
| 12 |
+
from torch.cuda.amp import autocast, GradScaler
|
| 13 |
+
from torch.utils.data import DataLoader, IterableDataset
|
| 14 |
|
| 15 |
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
if str(ROOT) not in sys.path:
|
| 17 |
+
sys.path.insert(0, str(ROOT))
|
| 18 |
|
| 19 |
+
from datasets.streaming import load_streaming_dataset
|
| 20 |
from model.transformer import MarsLMConfig, MarsLMForCausalLM
|
| 21 |
from tokenizer.tokenizer_utils import load_tokenizer, encode_text
|
| 22 |
|
|
|
|
| 24 |
def load_config(path: Path):
|
| 25 |
with path.open("r", encoding="utf-8") as handle:
|
| 26 |
raw = yaml.safe_load(handle)
|
| 27 |
+
config = MarsLMConfig.from_dict(raw)
|
| 28 |
+
config.extra["training"] = raw.get("training", {})
|
| 29 |
+
config.extra["system"] = raw.get("system", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
return config, raw
|
| 31 |
|
| 32 |
|
|
|
|
| 35 |
if train_path.suffix == ".pt":
|
| 36 |
payload = torch.load(train_path, map_location="cpu")
|
| 37 |
tokens = payload["tokens"]
|
| 38 |
+
elif train_path.suffix == ".jsonl":
|
| 39 |
+
ids = []
|
| 40 |
+
for line in train_path.read_text(encoding="utf-8").splitlines():
|
| 41 |
+
if not line.strip():
|
| 42 |
+
continue
|
| 43 |
+
ids.extend(encode_text(tokenizer, line.strip(), add_special_tokens=False))
|
| 44 |
+
tokens = torch.tensor(ids, dtype=torch.long)
|
| 45 |
else:
|
| 46 |
text = train_path.read_text(encoding="utf-8")
|
| 47 |
+
ids = encode_text(tokenizer, text, add_special_tokens=False)
|
| 48 |
+
tokens = torch.tensor(ids, dtype=torch.long)
|
| 49 |
+
|
| 50 |
+
if len(tokens) < block_size:
|
| 51 |
+
raise ValueError("The corpus is too small for the requested block size")
|
| 52 |
+
return tokens[: (len(tokens) // block_size) * block_size].view(-1, block_size)
|
| 53 |
|
| 54 |
|
| 55 |
def save_checkpoint(path: Path, model: nn.Module, optimizer, scheduler, epoch: int, step: int, config: MarsLMConfig):
|
|
|
|
| 75 |
return payload["epoch"], payload["step"]
|
| 76 |
|
| 77 |
|
| 78 |
+
def evaluate_dataset(model: nn.Module, loader: DataLoader, device: torch.device) -> float:
|
| 79 |
+
model.eval()
|
| 80 |
+
total_loss = 0.0
|
| 81 |
+
total_tokens = 0
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
for batch_tokens in loader:
|
| 84 |
+
if isinstance(batch_tokens, (list, tuple)):
|
| 85 |
+
batch_tokens = batch_tokens[0]
|
| 86 |
+
batch_tokens = batch_tokens.to(device)
|
| 87 |
+
logits, _ = model(batch_tokens)
|
| 88 |
+
shift_logits = logits[:, :-1, :].contiguous().view(-1, model.config.vocab_size)
|
| 89 |
+
shift_labels = batch_tokens[:, 1:].contiguous().view(-1)
|
| 90 |
+
loss = F.cross_entropy(shift_logits, shift_labels, reduction="sum")
|
| 91 |
+
total_loss += loss.item()
|
| 92 |
+
total_tokens += shift_labels.numel()
|
| 93 |
+
model.train()
|
| 94 |
+
return total_loss / max(total_tokens, 1)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
def main():
|
| 98 |
parser = argparse.ArgumentParser(description="Train a MarsLM model")
|
| 99 |
parser.add_argument("--config", default=str(ROOT / "configs" / "marslm-100M.yaml"))
|
|
|
|
| 109 |
parser.add_argument("--gradient-accumulation-steps", type=int, default=None)
|
| 110 |
parser.add_argument("--warmup-steps", type=int, default=None)
|
| 111 |
parser.add_argument("--max-steps", type=int, default=None)
|
| 112 |
+
parser.add_argument("--use-fp16", type=lambda x: bool(int(x)), default=None, help="Enable mixed precision training on CUDA")
|
| 113 |
+
parser.add_argument("--gradient-checkpointing", action="store_true", help="Enable gradient checkpointing during training")
|
| 114 |
+
parser.add_argument("--eval-file", default=None, help="Validation dataset source for periodic evaluation")
|
| 115 |
+
parser.add_argument("--eval-batch-size", type=int, default=None)
|
| 116 |
+
parser.add_argument("--eval-interval", type=int, default=None, help="Run validation every N optimization steps")
|
| 117 |
parser.add_argument("--resume", default=None)
|
| 118 |
args = parser.parse_args()
|
| 119 |
|
| 120 |
config_path = Path(args.config).resolve()
|
| 121 |
config, raw = load_config(config_path)
|
| 122 |
+
train_file_arg = args.train_file
|
| 123 |
+
train_path = Path(train_file_arg)
|
| 124 |
+
train_source = train_path.resolve() if train_path.exists() else train_file_arg
|
| 125 |
tokenizer_path = Path(args.tokenizer_model).resolve()
|
| 126 |
output_dir = Path(args.output_dir).resolve()
|
| 127 |
output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 137 |
args.checkpoint_interval = args.checkpoint_interval if args.checkpoint_interval is not None else int(training_cfg.get("checkpoint_interval", 200))
|
| 138 |
args.gradient_accumulation_steps = args.gradient_accumulation_steps if args.gradient_accumulation_steps is not None else int(training_cfg.get("gradient_accumulation_steps", 1))
|
| 139 |
args.warmup_steps = args.warmup_steps if args.warmup_steps is not None else int(training_cfg.get("warmup_steps", 50))
|
| 140 |
+
args.use_fp16 = args.use_fp16 if args.use_fp16 is not None else bool(training_cfg.get("use_fp16", False))
|
| 141 |
+
args.eval_batch_size = args.eval_batch_size if args.eval_batch_size is not None else int(training_cfg.get("eval_batch_size", 1))
|
| 142 |
+
args.eval_interval = args.eval_interval if args.eval_interval is not None else int(training_cfg.get("eval_interval", 0))
|
| 143 |
|
| 144 |
requested_device = system_cfg.get("device", "auto")
|
| 145 |
if requested_device in {"auto", "cuda", "gpu"} and torch.cuda.is_available():
|
|
|
|
| 152 |
torch.set_num_threads(int(system_cfg.get("torch_threads", 4)))
|
| 153 |
print(f"Using device: {device}")
|
| 154 |
|
| 155 |
+
config.gradient_checkpointing = args.gradient_checkpointing or bool(training_cfg.get("gradient_checkpointing", False))
|
| 156 |
+
tokenizer = load_tokenizer(tokenizer_path)
|
| 157 |
+
dataset = load_streaming_dataset(train_source, tokenizer, block_size=args.block_size)
|
| 158 |
+
shuffle = not isinstance(dataset, IterableDataset)
|
| 159 |
+
loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=shuffle, num_workers=0)
|
| 160 |
+
|
| 161 |
+
eval_loader = None
|
| 162 |
+
if args.eval_file and args.eval_interval > 0:
|
| 163 |
+
eval_source = Path(args.eval_file)
|
| 164 |
+
eval_source = eval_source.resolve() if eval_source.exists() else args.eval_file
|
| 165 |
+
eval_dataset = load_streaming_dataset(eval_source, tokenizer, block_size=args.block_size)
|
| 166 |
+
eval_loader = DataLoader(eval_dataset, batch_size=args.eval_batch_size, shuffle=False, num_workers=0)
|
| 167 |
|
| 168 |
model = MarsLMForCausalLM(config).to(device)
|
| 169 |
optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 170 |
grad_accum_steps = max(1, args.gradient_accumulation_steps)
|
| 171 |
+
max_steps = args.max_steps
|
| 172 |
|
| 173 |
def lr_lambda(step):
|
| 174 |
if step < args.warmup_steps:
|
| 175 |
return (step + 1) / max(1, args.warmup_steps)
|
| 176 |
+
if max_steps is None:
|
| 177 |
+
return 1.0
|
| 178 |
if step >= max_steps:
|
| 179 |
return 0.0
|
| 180 |
progress = (step - args.warmup_steps) / max(1, max_steps - args.warmup_steps)
|
|
|
|
| 188 |
start_epoch, step = load_checkpoint(Path(args.resume).resolve(), model, optimizer, scheduler)
|
| 189 |
print(f"Resumed from {args.resume}")
|
| 190 |
|
| 191 |
+
use_amp = args.use_fp16 and device.type == "cuda"
|
| 192 |
+
scaler = GradScaler() if use_amp else None
|
| 193 |
+
if args.use_fp16 and not use_amp:
|
| 194 |
+
print("FP16 requested but CUDA is not available; training will use float32.")
|
| 195 |
+
|
| 196 |
model.train()
|
| 197 |
optimizer.zero_grad(set_to_none=True)
|
| 198 |
for epoch in range(start_epoch, args.epochs):
|
| 199 |
+
for batch_idx, batch_tokens in enumerate(loader):
|
| 200 |
+
if isinstance(batch_tokens, (list, tuple)):
|
| 201 |
+
batch_tokens = batch_tokens[0]
|
| 202 |
batch_tokens = batch_tokens.to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
with autocast(enabled=use_amp):
|
| 205 |
+
logits, _ = model(batch_tokens)
|
| 206 |
+
shift_logits = logits[:, :-1, :].contiguous().view(-1, config.vocab_size)
|
| 207 |
+
shift_labels = batch_tokens[:, 1:].contiguous().view(-1)
|
| 208 |
+
loss = F.cross_entropy(shift_logits, shift_labels) / grad_accum_steps
|
| 209 |
+
|
| 210 |
+
if use_amp:
|
| 211 |
+
scaler.scale(loss).backward()
|
| 212 |
+
else:
|
| 213 |
+
loss.backward()
|
| 214 |
+
|
| 215 |
+
if (batch_idx + 1) % grad_accum_steps == 0:
|
| 216 |
+
if use_amp:
|
| 217 |
+
scaler.unscale_(optimizer)
|
| 218 |
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 219 |
+
if use_amp:
|
| 220 |
+
scaler.step(optimizer)
|
| 221 |
+
scaler.update()
|
| 222 |
+
else:
|
| 223 |
+
optimizer.step()
|
| 224 |
optimizer.zero_grad(set_to_none=True)
|
| 225 |
scheduler.step()
|
| 226 |
step += 1
|
| 227 |
|
| 228 |
+
if args.checkpoint_interval and step % args.checkpoint_interval == 0:
|
| 229 |
checkpoint_path = output_dir / f"checkpoint-epoch{epoch + 1:02d}-step{step:06d}.pt"
|
| 230 |
save_checkpoint(checkpoint_path, model, optimizer, scheduler, epoch + 1, step, config)
|
| 231 |
+
save_checkpoint(output_dir / "checkpoint-last.pt", model, optimizer, scheduler, epoch + 1, step, config)
|
| 232 |
print(f"Saved checkpoint {checkpoint_path} with loss {loss.item():.4f}")
|
| 233 |
|
| 234 |
+
if eval_loader is not None and args.eval_interval > 0 and step % args.eval_interval == 0:
|
| 235 |
+
val_loss = evaluate_dataset(model, eval_loader, device)
|
| 236 |
+
print(f"Validation at step {step}: loss={val_loss:.4f}, perplexity={math.exp(val_loss):.2f}")
|
| 237 |
+
|
| 238 |
+
if args.max_steps is not None and step >= args.max_steps:
|
| 239 |
break
|
| 240 |
|
| 241 |
+
if args.max_steps is not None and step >= args.max_steps:
|
| 242 |
break
|
| 243 |
|
| 244 |
+
epoch_model_path = output_dir / f"marslm-epoch{epoch + 1:02d}.pt"
|
| 245 |
+
torch.save(model.state_dict(), epoch_model_path)
|
| 246 |
+
print(f"Saved model for epoch {epoch + 1} to {epoch_model_path}")
|
| 247 |
|
| 248 |
final_path = output_dir / "marslm-final.pt"
|
| 249 |
torch.save(model.state_dict(), final_path)
|
| 250 |
+
checkpoint_path = output_dir / "checkpoint-last.pt"
|
| 251 |
+
save_checkpoint(checkpoint_path, model, optimizer, scheduler, args.epochs, step, config)
|
| 252 |
+
with (output_dir / "config.json").open("w", encoding="utf-8") as handle:
|
| 253 |
+
json.dump(config.to_dict(), handle, indent=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
print(f"Training complete. Final weights saved to {final_path}")
|
| 255 |
|
| 256 |
|