reflexlm 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
reflexlm/__init__.py ADDED
@@ -0,0 +1,80 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """reflexlm: Pretraining, CPT, SFT, and Post-Training for System-1 SLMs."""
3
+
4
+ from reflexlm.config import (
5
+ CPTConfig,
6
+ PipelineConfig,
7
+ PostTrainConfig,
8
+ PretrainConfig,
9
+ SFTConfig,
10
+ SLMArchitectureConfig,
11
+ )
12
+ from reflexlm.data import (
13
+ IGNORE_INDEX,
14
+ DeterministicTokenizer,
15
+ MaskedSFTExample,
16
+ PreferenceExample,
17
+ build_sft_loss_mask,
18
+ load_preference_jsonl,
19
+ load_sft_jsonl,
20
+ load_text_jsonl,
21
+ mix_cpt_replay_stream,
22
+ pack_token_sequences,
23
+ strip_system2_thinking,
24
+ )
25
+ from reflexlm.inference import HARDWARE_PROFILES, System1BudgetReport, audit_system1_budget
26
+ from reflexlm.losses import (
27
+ dpo_loss,
28
+ orpo_loss,
29
+ simpo_loss,
30
+ system1_distill_loss,
31
+ )
32
+ from reflexlm.pipeline import (
33
+ StageSummary,
34
+ evaluate_posttrain_step,
35
+ plan_cpt_stage,
36
+ plan_posttrain_stage,
37
+ plan_pretrain_stage,
38
+ plan_sft_stage,
39
+ run_stage_from_files,
40
+ )
41
+ from reflexlm.schedules import cosine_lr, wsd_lr
42
+
43
+ __version__ = "0.2.0"
44
+
45
+ __all__ = [
46
+ "CPTConfig",
47
+ "DeterministicTokenizer",
48
+ "HARDWARE_PROFILES",
49
+ "IGNORE_INDEX",
50
+ "MaskedSFTExample",
51
+ "PipelineConfig",
52
+ "PostTrainConfig",
53
+ "PreferenceExample",
54
+ "PretrainConfig",
55
+ "SFTConfig",
56
+ "SLMArchitectureConfig",
57
+ "StageSummary",
58
+ "System1BudgetReport",
59
+ "__version__",
60
+ "audit_system1_budget",
61
+ "build_sft_loss_mask",
62
+ "cosine_lr",
63
+ "dpo_loss",
64
+ "evaluate_posttrain_step",
65
+ "load_preference_jsonl",
66
+ "load_sft_jsonl",
67
+ "load_text_jsonl",
68
+ "mix_cpt_replay_stream",
69
+ "orpo_loss",
70
+ "pack_token_sequences",
71
+ "plan_cpt_stage",
72
+ "plan_posttrain_stage",
73
+ "plan_pretrain_stage",
74
+ "plan_sft_stage",
75
+ "run_stage_from_files",
76
+ "simpo_loss",
77
+ "strip_system2_thinking",
78
+ "system1_distill_loss",
79
+ "wsd_lr",
80
+ ]
reflexlm/cli.py ADDED
@@ -0,0 +1,205 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """CLI entrypoint for reflexlm."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from pathlib import Path
8
+ from typing import cast
9
+
10
+ import click
11
+ from pydantic import ValidationError
12
+
13
+ from reflexlm.config import PipelineConfig, SLMArchitectureConfig
14
+ from reflexlm.data import strip_system2_thinking
15
+ from reflexlm.inference import HARDWARE_PROFILES, KvDtype, WeightDtype, audit_system1_budget
16
+ from reflexlm.pipeline import run_stage_from_files
17
+
18
+ _PRESETS: dict[str, SLMArchitectureConfig] = {
19
+ "sys1-150m": SLMArchitectureConfig(
20
+ name="sys1-150m",
21
+ vocab_size=32_000,
22
+ hidden_size=768,
23
+ intermediate_size=2048,
24
+ num_layers=14,
25
+ num_heads=12,
26
+ num_kv_heads=4,
27
+ max_seq_len=4096,
28
+ ),
29
+ "sys1-350m": SLMArchitectureConfig(
30
+ name="sys1-350m",
31
+ vocab_size=32_000,
32
+ hidden_size=1024,
33
+ intermediate_size=2816,
34
+ num_layers=20,
35
+ num_heads=16,
36
+ num_kv_heads=4,
37
+ max_seq_len=4096,
38
+ ),
39
+ "sys1-1b": SLMArchitectureConfig(
40
+ name="sys1-1b",
41
+ vocab_size=49_152,
42
+ hidden_size=1792,
43
+ intermediate_size=4864,
44
+ num_layers=24,
45
+ num_heads=14,
46
+ num_kv_heads=2,
47
+ max_seq_len=8192,
48
+ ),
49
+ }
50
+
51
+
52
+ def _load_config_or_die(path: Path) -> PipelineConfig:
53
+ try:
54
+ return PipelineConfig.from_yaml(path)
55
+ except (OSError, ValueError, ValidationError) as exc:
56
+ raise click.ClickException(f"Invalid recipe {path}: {exc}") from exc
57
+
58
+
59
+ @click.group()
60
+ @click.version_option(package_name="reflexlm")
61
+ def main() -> None:
62
+ """reflexlm: Pretraining, CPT, SFT & Post-Training for System-1 SLMs."""
63
+
64
+
65
+ @main.command("init")
66
+ @click.option(
67
+ "--preset",
68
+ type=click.Choice(sorted(_PRESETS)),
69
+ default="sys1-350m",
70
+ show_default=True,
71
+ help="Built-in System-1 SLM architecture preset.",
72
+ )
73
+ @click.option(
74
+ "--output",
75
+ type=click.Path(path_type=Path),
76
+ default=Path("reflexlm.yaml"),
77
+ show_default=True,
78
+ help="Destination YAML recipe file.",
79
+ )
80
+ def init_recipe(preset: str, output: Path) -> None:
81
+ """Generate a full Pretrain -> CPT -> SFT -> Post-Train YAML recipe."""
82
+ cfg = PipelineConfig(architecture=_PRESETS[preset])
83
+ cfg.to_yaml(output)
84
+ params_m = cfg.architecture.estimate_parameters() / 1e6
85
+ click.echo(f"Wrote {preset} (~{params_m:.1f}M params) recipe to {output}")
86
+
87
+
88
+ @main.command("audit")
89
+ @click.option(
90
+ "--config",
91
+ "config_path",
92
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
93
+ default=None,
94
+ help="Path to reflexlm.yaml (uses sys1-350m preset if omitted).",
95
+ )
96
+ @click.option(
97
+ "--hardware",
98
+ type=click.Choice(sorted(HARDWARE_PROFILES)),
99
+ default="L4",
100
+ show_default=True,
101
+ )
102
+ @click.option(
103
+ "--weight-dtype",
104
+ type=click.Choice(["fp16", "bf16", "int8", "int4"]),
105
+ default="bf16",
106
+ show_default=True,
107
+ )
108
+ @click.option(
109
+ "--kv-dtype",
110
+ type=click.Choice(["fp16", "bf16", "fp8"]),
111
+ default="fp8",
112
+ show_default=True,
113
+ )
114
+ @click.option("--concurrency", type=click.IntRange(min=1), default=16, show_default=True)
115
+ @click.option("--prompt-tokens", type=click.IntRange(min=0), default=256, show_default=True)
116
+ @click.option("--target-tokens", type=click.IntRange(min=1), default=64, show_default=True)
117
+ @click.option(
118
+ "--sla-ms",
119
+ type=click.FloatRange(min=0.0, min_open=True),
120
+ default=500.0,
121
+ show_default=True,
122
+ )
123
+ @click.option("--json-output", is_flag=True, help="Emit machine-readable JSON.")
124
+ def audit_cmd(
125
+ config_path: Path | None,
126
+ hardware: str,
127
+ weight_dtype: str,
128
+ kv_dtype: str,
129
+ concurrency: int,
130
+ prompt_tokens: int,
131
+ target_tokens: int,
132
+ sla_ms: float,
133
+ json_output: bool,
134
+ ) -> None:
135
+ """Audit System-1 VRAM, GQA KV-cache footprint, TTFT, and decode latency."""
136
+ arch = _load_config_or_die(config_path).architecture if config_path else _PRESETS["sys1-350m"]
137
+ report = audit_system1_budget(
138
+ arch,
139
+ hardware=hardware,
140
+ weight_dtype=cast(WeightDtype, weight_dtype),
141
+ kv_dtype=cast(KvDtype, kv_dtype),
142
+ concurrency=concurrency,
143
+ prompt_tokens=prompt_tokens,
144
+ target_output_tokens=target_tokens,
145
+ system1_sla_ms=sla_ms,
146
+ )
147
+ if json_output:
148
+ click.echo(json.dumps(report.to_dict(), indent=2))
149
+ return
150
+
151
+ click.echo(f"Model: {report.model_name} ({report.params_millions}M params)")
152
+ click.echo(f"Hardware: {report.hardware} | Fits: {report.fits_in_memory}")
153
+ click.echo(
154
+ f"Memory: weights={report.weights_gb} GB | "
155
+ f"KV/seq={report.kv_cache_per_seq_mb} MB | total={report.total_vram_gb} GB"
156
+ )
157
+ click.echo(
158
+ f"System-1 Perf: TTFT={report.est_ttft_ms} ms | {report.est_decode_tok_s} tok/s | "
159
+ f"total={report.est_response_latency_ms} ms "
160
+ f"(SLA <= {sla_ms} ms: {report.meets_system1_sla})"
161
+ )
162
+ click.echo(f"vLLM launch: {report.vllm_command}")
163
+
164
+
165
+ @main.command("plan")
166
+ @click.argument("stage", type=click.Choice(["pretrain", "cpt", "sft", "posttrain"]))
167
+ @click.option(
168
+ "--config",
169
+ "config_path",
170
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
171
+ default=Path("reflexlm.yaml"),
172
+ show_default=True,
173
+ )
174
+ @click.option(
175
+ "--base-dir",
176
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
177
+ default=Path("."),
178
+ show_default=True,
179
+ help="Base directory for resolving relative dataset paths in the recipe.",
180
+ )
181
+ @click.option("--json-output", is_flag=True, help="Emit machine-readable JSON.")
182
+ def plan_cmd(stage: str, config_path: Path, base_dir: Path, json_output: bool) -> None:
183
+ """Validate JSONL datasets and prepare packed/masked blocks for a pipeline stage."""
184
+ cfg = _load_config_or_die(config_path)
185
+ try:
186
+ summary = run_stage_from_files(cfg, stage, base_dir=base_dir)
187
+ except (FileNotFoundError, ValueError) as exc:
188
+ raise click.ClickException(str(exc)) from exc
189
+
190
+ if json_output:
191
+ click.echo(json.dumps(summary.to_dict(), indent=2))
192
+ return
193
+
194
+ click.echo(
195
+ f"[{summary.stage}] examples={summary.examples_in}->{summary.examples_out} | "
196
+ f"tokens={summary.tokens_total} | "
197
+ f"lr={summary.peak_lr}->{summary.final_lr} | {summary.notes}"
198
+ )
199
+
200
+
201
+ @main.command("strip-thinking")
202
+ @click.argument("text")
203
+ def strip_thinking_cmd(text: str) -> None:
204
+ """Strip System-2 thinking/planning traces into a clean System-1 target."""
205
+ click.echo(strip_system2_thinking(text))
reflexlm/config.py ADDED
@@ -0,0 +1,219 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Typed configurations for System-1 SLM pretraining, CPT, SFT, and post-training."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+ from typing import Literal
8
+
9
+ import yaml
10
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
11
+
12
+
13
+ class SLMArchitectureConfig(BaseModel):
14
+ """Compact decoder-only Transformer architecture (GQA + SwiGLU) for SLMs."""
15
+
16
+ model_config = ConfigDict(extra="forbid")
17
+
18
+ name: str = Field(
19
+ default="sys1-350m", min_length=1, description="Human-readable SLM preset name."
20
+ )
21
+ vocab_size: int = Field(default=32_000, ge=8)
22
+ hidden_size: int = Field(default=1024, gt=0)
23
+ intermediate_size: int = Field(default=2816, gt=0)
24
+ num_layers: int = Field(default=20, gt=0)
25
+ num_heads: int = Field(default=16, gt=0)
26
+ num_kv_heads: int = Field(default=4, gt=0, description="GQA KV heads for low-VRAM inference.")
27
+ max_seq_len: int = Field(default=4096, gt=0)
28
+ tie_embeddings: bool = Field(default=True, description="Tie input/output embeddings for SLMs.")
29
+
30
+ @model_validator(mode="after")
31
+ def _validate_heads(self) -> SLMArchitectureConfig:
32
+ if self.hidden_size % self.num_heads != 0:
33
+ raise ValueError("hidden_size must be divisible by num_heads")
34
+ if self.num_heads % self.num_kv_heads != 0:
35
+ raise ValueError("num_heads must be divisible by num_kv_heads")
36
+ return self
37
+
38
+ @property
39
+ def head_dim(self) -> int:
40
+ return self.hidden_size // self.num_heads
41
+
42
+ def estimate_parameters(self) -> int:
43
+ """Estimate total trainable parameter count (Llama-style GQA + SwiGLU)."""
44
+ embed = self.vocab_size * self.hidden_size
45
+ lm_head = 0 if self.tie_embeddings else embed
46
+ kv_dim = self.num_kv_heads * self.head_dim
47
+ attn = (2 * self.hidden_size * self.hidden_size) + (2 * self.hidden_size * kv_dim)
48
+ mlp = 3 * self.hidden_size * self.intermediate_size
49
+ norms = (2 * self.num_layers + 1) * self.hidden_size
50
+ return embed + lm_head + self.num_layers * (attn + mlp) + norms
51
+
52
+
53
+ class PretrainConfig(BaseModel):
54
+ """Stage 1: From-scratch SLM pretraining configuration."""
55
+
56
+ model_config = ConfigDict(extra="forbid")
57
+
58
+ dataset_path: str = Field(default="data/pretrain.jsonl", min_length=1)
59
+ output_dir: str = Field(default="runs/pretrain", min_length=1)
60
+ seq_len: int = Field(default=2048, gt=0)
61
+ micro_batch_size: int = Field(default=8, gt=0)
62
+ grad_accum_steps: int = Field(default=4, gt=0)
63
+ total_steps: int = Field(default=10_000, gt=0)
64
+ warmup_steps: int = Field(default=500, ge=0)
65
+ decay_steps: int = Field(default=1500, ge=0)
66
+ schedule: Literal["wsd", "cosine"] = "wsd"
67
+ peak_lr: float = Field(default=6e-4, gt=0)
68
+ min_lr: float = Field(default=6e-5, ge=0)
69
+ weight_decay: float = Field(default=0.1, ge=0)
70
+ pack_sequences: bool = True
71
+ seed: int = 42
72
+
73
+ @model_validator(mode="after")
74
+ def _validate_schedule(self) -> PretrainConfig:
75
+ if self.min_lr > self.peak_lr:
76
+ raise ValueError("min_lr cannot exceed peak_lr")
77
+ if self.warmup_steps > self.total_steps:
78
+ raise ValueError("warmup_steps cannot exceed total_steps")
79
+ if self.schedule == "wsd" and self.warmup_steps + self.decay_steps > self.total_steps:
80
+ raise ValueError(
81
+ "warmup_steps + decay_steps cannot exceed total_steps for WSD schedule"
82
+ )
83
+ return self
84
+
85
+
86
+ class CPTConfig(BaseModel):
87
+ """Stage 2: Continual Pretraining (CPT) with replay buffer to avoid forgetting."""
88
+
89
+ model_config = ConfigDict(extra="forbid")
90
+
91
+ base_checkpoint: str = Field(default="runs/pretrain/latest", min_length=1)
92
+ domain_dataset_path: str = Field(default="data/domain_cpt.jsonl", min_length=1)
93
+ replay_dataset_path: str | None = Field(
94
+ default="data/general_replay.jsonl",
95
+ description="General corpus mixed in to prevent catastrophic forgetting in SLMs.",
96
+ )
97
+ replay_ratio: float = Field(
98
+ default=0.15,
99
+ ge=0.0,
100
+ lt=1.0,
101
+ description="Fraction of general replay samples mixed into CPT.",
102
+ )
103
+ output_dir: str = Field(default="runs/cpt", min_length=1)
104
+ seq_len: int = Field(default=4096, gt=0)
105
+ micro_batch_size: int = Field(default=4, gt=0)
106
+ total_steps: int = Field(default=2000, gt=0)
107
+ warmup_steps: int = Field(default=100, ge=0)
108
+ decay_steps: int = Field(default=400, ge=0)
109
+ peak_lr: float = Field(default=1.5e-4, gt=0)
110
+ min_lr: float = Field(default=1.5e-5, ge=0)
111
+ weight_decay: float = Field(default=0.1, ge=0)
112
+ seed: int = 42
113
+
114
+ @model_validator(mode="after")
115
+ def _validate_schedule(self) -> CPTConfig:
116
+ if self.min_lr > self.peak_lr:
117
+ raise ValueError("min_lr cannot exceed peak_lr")
118
+ if self.warmup_steps + self.decay_steps > self.total_steps:
119
+ raise ValueError("warmup_steps + decay_steps cannot exceed total_steps")
120
+ return self
121
+
122
+
123
+ class SFTConfig(BaseModel):
124
+ """Stage 3: System-1 Supervised Fine-Tuning (concise, direct, assistant-only loss)."""
125
+
126
+ model_config = ConfigDict(extra="forbid")
127
+
128
+ base_checkpoint: str = Field(default="runs/cpt/latest", min_length=1)
129
+ dataset_path: str = Field(default="data/sft.jsonl", min_length=1)
130
+ output_dir: str = Field(default="runs/sft", min_length=1)
131
+ max_seq_len: int = Field(default=2048, gt=0)
132
+ max_target_tokens: int = Field(
133
+ default=256,
134
+ gt=0,
135
+ description="System-1 response length budget to discourage verbose drift.",
136
+ )
137
+ strip_thinking_tags: bool = Field(
138
+ default=True,
139
+ description="Strip System-2 <think>/planning blocks when distilling into System-1.",
140
+ )
141
+ assistant_only_loss: bool = True
142
+ use_lora: bool = True
143
+ lora_r: int = Field(default=16, gt=0)
144
+ lora_alpha: int = Field(default=32, gt=0)
145
+ lora_target_modules: list[str] = Field(
146
+ default_factory=lambda: ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj"]
147
+ )
148
+ micro_batch_size: int = Field(default=4, gt=0)
149
+ learning_rate: float = Field(default=2e-4, gt=0)
150
+ epochs: int = Field(default=3, gt=0)
151
+ seed: int = 42
152
+
153
+ @model_validator(mode="after")
154
+ def _validate_sft(self) -> SFTConfig:
155
+ if self.max_target_tokens > self.max_seq_len:
156
+ raise ValueError("max_target_tokens cannot exceed max_seq_len")
157
+ if self.use_lora and not self.lora_target_modules:
158
+ raise ValueError("lora_target_modules cannot be empty when use_lora=True")
159
+ return self
160
+
161
+
162
+ class PostTrainConfig(BaseModel):
163
+ """Stage 4: Reference-free / System-1 post-training (SimPO, ORPO, DPO, Distillation)."""
164
+
165
+ model_config = ConfigDict(extra="forbid")
166
+
167
+ base_checkpoint: str = Field(default="runs/sft/latest", min_length=1)
168
+ dataset_path: str = Field(default="data/preferences.jsonl", min_length=1)
169
+ output_dir: str = Field(default="runs/posttrain", min_length=1)
170
+ method: Literal["simpo", "orpo", "dpo", "sys1_distill"] = Field(
171
+ default="simpo",
172
+ description="SimPO and ORPO need no reference model, ideal for single-GPU SLMs.",
173
+ )
174
+ beta: float = Field(default=2.0, gt=0)
175
+ gamma: float = Field(
176
+ default=0.5,
177
+ ge=0.0,
178
+ description="SimPO target reward margin separating chosen vs rejected responses.",
179
+ )
180
+ length_penalty: float = Field(
181
+ default=0.05,
182
+ ge=0.0,
183
+ description="Extra System-1 conciseness penalty on overly verbose completions.",
184
+ )
185
+ distill_temperature: float = Field(default=2.0, gt=0)
186
+ distill_alpha: float = Field(default=0.7, ge=0.0, le=1.0)
187
+ micro_batch_size: int = Field(default=4, gt=0)
188
+ learning_rate: float = Field(default=5e-5, gt=0)
189
+ total_steps: int = Field(default=1000, gt=0)
190
+ seed: int = 42
191
+
192
+
193
+ class PipelineConfig(BaseModel):
194
+ """Full end-to-end System-1 SLM recipe."""
195
+
196
+ model_config = ConfigDict(extra="forbid")
197
+
198
+ architecture: SLMArchitectureConfig = Field(default_factory=SLMArchitectureConfig)
199
+ pretrain: PretrainConfig = Field(default_factory=PretrainConfig)
200
+ cpt: CPTConfig = Field(default_factory=CPTConfig)
201
+ sft: SFTConfig = Field(default_factory=SFTConfig)
202
+ posttrain: PostTrainConfig = Field(default_factory=PostTrainConfig)
203
+
204
+ @classmethod
205
+ def from_yaml(cls, path: str | Path) -> PipelineConfig:
206
+ loaded = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
207
+ if loaded is None:
208
+ loaded = {}
209
+ if not isinstance(loaded, dict):
210
+ raise ValueError(f"YAML recipe root must be a mapping, got {type(loaded).__name__}")
211
+ return cls.model_validate(loaded)
212
+
213
+ def to_yaml(self, path: str | Path) -> None:
214
+ dest = Path(path)
215
+ dest.parent.mkdir(parents=True, exist_ok=True)
216
+ dest.write_text(
217
+ yaml.safe_dump(self.model_dump(), sort_keys=False),
218
+ encoding="utf-8",
219
+ )