meridianal commited on
Commit
5c78e0e
Β·
verified Β·
1 Parent(s): f75c77c

docs: update model card for v6.0.0

Browse files
Files changed (1) hide show
  1. README.md +466 -422
README.md CHANGED
@@ -1,422 +1,466 @@
1
- # Meridian.AI β€” Continual-Learning Finance LLM
2
-
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
4
- [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
5
- [![Architecture](https://img.shields.io/badge/Architecture-Sparse_MoE-success.svg)](https://huggingface.co/meridianal/FinAI)
6
- [![Training](https://img.shields.io/badge/Training-Hourly_CI-orange.svg)](https://github.com/MeridianAlgo/FinAI/actions)
7
- [![HuggingFace](https://img.shields.io/badge/HuggingFace-meridianal%2FFinAI-yellow.svg)](https://huggingface.co/meridianal/FinAI)
8
- [![Version](https://img.shields.io/badge/version-5.1.0-blueviolet.svg)]()
9
-
10
- Meridian.AI is a finance-specialized language model that trains itself continuously, every hour, entirely on free GitHub Actions infrastructure. It uses a **Sparse Mixture-of-Experts (SMoE)** architecture with a **Qwen2.5-0.5B** backbone fine-tuned via **Elastic Weight Consolidation (EWC)** to prevent catastrophic forgetting across training sessions.
11
-
12
- **Model checkpoints:** [huggingface.co/meridianal/FinAI](https://huggingface.co/meridianal/FinAI)
13
-
14
- ---
15
-
16
- ## Table of Contents
17
-
18
- - [Why Meridian.AI](#why-meridianai)
19
- - [Key Technical Innovations](#key-technical-innovations)
20
- - [Architecture](#architecture)
21
- - [Quick Start](#quick-start)
22
- - [Inference](#inference)
23
- - [Local Training](#local-training)
24
- - [Environment Variables Reference](#environment-variables-reference)
25
- - [CI/CD Training Pipeline](#cicd-training-pipeline)
26
- - [Dataset Curriculum](#dataset-curriculum)
27
- - [Repository Structure](#repository-structure)
28
- - [Troubleshooting](#troubleshooting)
29
- - [Disclaimer](#disclaimer)
30
-
31
- ---
32
-
33
- ## Why Meridian.AI
34
-
35
- Standard LLMs have a static knowledge cutoff. For finance β€” where earnings reports, Fed decisions, and market conditions change daily β€” this is a critical limitation.
36
-
37
- Meridian.AI solves this with an **automated continuous training pipeline**: every hour, GitHub Actions pulls the latest checkpoint from HuggingFace, trains on fresh financial data, and pushes the updated checkpoint back. No GPUs. No cloud bills. No manual intervention.
38
-
39
- Key constraints this design respects:
40
- - **16 GB RAM** ceiling of free GitHub Actions ubuntu-latest runners
41
- - **2000 CI minutes/month** free tier (public repos: unlimited)
42
- - **No persistent storage** between runs β€” all state is round-tripped through HuggingFace Hub
43
-
44
- ---
45
-
46
- ## Key Technical Innovations
47
-
48
- ### 1. Sparse Mixture-of-Experts (SMoE)
49
- Each MoE layer contains 8 expert feed-forward networks. For each input token, a learned router selects the top-2 most relevant experts. Only those 2 run β€” the other 6 are skipped. This gives a large total parameter count (~479M) with a much smaller active compute cost (~283M parameters per forward pass).
50
-
51
- A load-balancing auxiliary loss (Switch Transformer style) ensures experts are used evenly and no single expert dominates routing.
52
-
53
- ### 2. Elastic Weight Consolidation (EWC)
54
- After each hourly training run, the model computes the diagonal Fisher Information Matrix β€” a measure of which parameters were most important for tasks learned so far. The next run adds a regularization penalty for changing those parameters. This prevents the model from "forgetting" financial knowledge from earlier training sessions while absorbing new data.
55
-
56
- ### 3. Financial Numeracy Encoding
57
- Standard tokenizers treat numbers as arbitrary tokens. Meridian.AI adds a 64-dimensional learned embedding specifically allocated to encode numeric magnitude signals, giving the model dedicated capacity to reason about quantities like prices, percentages, and financial ratios.
58
-
59
- ### 4. Memory-Safe CPU Training
60
- Every component is designed around the 16 GB RAM constraint:
61
- - **AdaFactor** optimizer: eliminates the 2Γ—-parameter-size optimizer state of Adam
62
- - **Gradient checkpointing**: trades compute for activation memory
63
- - **Soft RAM throttle**: dynamically truncates sequence length when memory pressure rises
64
- - **Hard RAM guard**: emergency checkpoint + clean exit before OOM
65
- - **Fisher threshold pruning**: only stores EWC state for parameters with significant Fisher values
66
-
67
- ---
68
-
69
- ## Architecture
70
-
71
- | Specification | Value |
72
- |:---|:---|
73
- | Base Model | Qwen2.5-0.5B (continually fine-tuned) |
74
- | Custom Arch Module | Sparse MoE Transformer (meridian/) |
75
- | Layers | 14 (alternating Dense ↔ MoE) |
76
- | Attention | Grouped Query Attention: 12 Q heads, 4 KV heads |
77
- | Position Encoding | RoPE (theta=500,000) |
78
- | Feed-Forward | SwiGLU |
79
- | Normalization | RMSNorm |
80
- | MoE Experts | 8 per layer, top-2 active per token |
81
- | Vocabulary | 151,665 tokens (Qwen2.5 tokenizer) |
82
- | Context Window | 2,048 tokens |
83
- | Total Parameters | ~479M (tied) / ~283M unique |
84
- | Active per Token | ~283M |
85
- | Continual Learning | Elastic Weight Consolidation (EWC) |
86
-
87
- Layer alternation pattern (0-indexed):
88
- ```
89
- Layer 0: Dense FFN
90
- Layer 1: Sparse MoE (8 experts)
91
- Layer 2: Dense FFN
92
- Layer 3: Sparse MoE (8 experts)
93
- ... (alternates for all 14 layers)
94
- ```
95
-
96
- For full architectural detail, see [docs/architecture.md](docs/architecture.md).
97
-
98
- ---
99
-
100
- ## Quick Start
101
-
102
- ### Prerequisites
103
- - Python 3.10+
104
- - Git
105
- - ~2 GB disk (for model weights)
106
-
107
- ### Installation
108
-
109
- ```bash
110
- git clone https://github.com/MeridianAlgo/FinAI.git
111
- cd FinAI
112
- pip install -r requirements.txt
113
- ```
114
-
115
- ### Verify Installation (Smoke Test)
116
-
117
- Runs a tiny in-memory model to confirm the architecture works without downloading anything:
118
-
119
- ```bash
120
- SMOKE_TEST=1 FAST_MODE=1 python train.py
121
- ```
122
-
123
- Expected output: `[OK] Smoke test passed!`
124
-
125
- ---
126
-
127
- ## Inference
128
-
129
- ### From HuggingFace Hub
130
-
131
- ```python
132
- import torch
133
- from transformers import AutoModelForCausalLM, AutoTokenizer
134
-
135
- repo_id = "meridianal/FinAI"
136
-
137
- tokenizer = AutoTokenizer.from_pretrained(repo_id, subfolder="checkpoint")
138
- model = AutoModelForCausalLM.from_pretrained(
139
- repo_id,
140
- subfolder="checkpoint",
141
- trust_remote_code=True,
142
- torch_dtype=torch.float32,
143
- low_cpu_mem_usage=True,
144
- )
145
- model.eval()
146
-
147
- prompt = """### Instruction:
148
- Explain the difference between a bond's yield to maturity and its coupon rate.
149
-
150
- ### Response:
151
- """
152
-
153
- inputs = tokenizer(prompt, return_tensors="pt")
154
-
155
- with torch.no_grad():
156
- output = model.generate(
157
- **inputs,
158
- max_new_tokens=200,
159
- do_sample=True,
160
- temperature=0.8,
161
- top_p=0.92,
162
- repetition_penalty=1.3,
163
- no_repeat_ngram_size=3,
164
- pad_token_id=tokenizer.pad_token_id,
165
- eos_token_id=tokenizer.eos_token_id,
166
- )
167
-
168
- print(tokenizer.decode(output[0], skip_special_tokens=True))
169
- ```
170
-
171
- ### From Local Checkpoint
172
-
173
- If you have trained locally and have a `./checkpoint` directory:
174
-
175
- ```python
176
- from transformers import AutoModelForCausalLM, AutoTokenizer
177
-
178
- tokenizer = AutoTokenizer.from_pretrained("./checkpoint")
179
- model = AutoModelForCausalLM.from_pretrained("./checkpoint")
180
- ```
181
-
182
- See [docs/examples/01_inference.py](docs/examples/01_inference.py) for a complete, annotated script.
183
-
184
- ---
185
-
186
- ## Local Training
187
-
188
- ### Full Training Run
189
-
190
- ```bash
191
- export HF_TOKEN=your_huggingface_token
192
- python train.py
193
- ```
194
-
195
- The script will:
196
- 1. Pull the latest checkpoint from HuggingFace (if `HF_TOKEN` is set)
197
- 2. Load the Qwen2.5-0.5B base model (or resume from checkpoint)
198
- 3. Stream finance datasets and train for `MAX_STEPS` steps
199
- 4. Save checkpoint locally (and upload if token is present)
200
-
201
- ### Fast Debugging Mode
202
-
203
- Runs with minimal settings (no dataset streaming, 5 steps, tiny sequences):
204
-
205
- ```bash
206
- FAST_MODE=1 python train.py
207
- ```
208
-
209
- ### Custom Step Count
210
-
211
- ```bash
212
- MAX_STEPS=300 BATCH_SIZE=1 python train.py
213
- ```
214
-
215
- ---
216
-
217
- ## Environment Variables Reference
218
-
219
- All variables are optional. CI defaults are shown in `train.yml`.
220
-
221
- ### Core Training
222
-
223
- | Variable | CI Default | Description |
224
- |:---|:---|:---|
225
- | `MAX_STEPS` | `150` | Gradient update steps per run |
226
- | `TOTAL_STEPS` | `100000` | Cumulative steps across all runs (for LR schedule) |
227
- | `BATCH_SIZE` | `1` | Samples per micro-step |
228
- | `GRAD_ACCUM` | `8` | Micro-steps before each optimizer update |
229
- | `LEARNING_RATE` | `5e-5` | Peak learning rate |
230
- | `BLOCK_SIZE` | `256` | Token sequence length |
231
- | `DTYPE` | `bfloat16` | Model dtype (`bfloat16` or `float32`) |
232
- | `OPTIMIZER` | `adafactor` | Optimizer (`adafactor` or `adamw`) |
233
-
234
- ### Memory Management
235
-
236
- | Variable | CI Default | Description |
237
- |:---|:---|:---|
238
- | `HARD_RAM_GUARD` | `1` | Enable emergency save + stop at RAM ceiling |
239
- | `MAX_RAM_GB` | `14.5` | Hard RAM limit in GB |
240
- | `SOFT_RAM_GB` | `12.5` | Soft limit β€” begins sequence truncation |
241
- | `SOFT_RAM_PCT` | `80` | Soft limit as % of total RAM |
242
- | `MIN_THROTTLE_SEQ_LEN` | `64` | Minimum sequence length during throttle |
243
- | `GRADIENT_CHECKPOINTING` | `1` | Trade compute for activation memory |
244
- | `SKIP_OPTIMIZER_SAVE` | `1` | Omit 2GB+ optimizer state from checkpoint |
245
-
246
- ### Dataset
247
-
248
- | Variable | CI Default | Description |
249
- |:---|:---|:---|
250
- | `MAX_BYTES` | `15728640` (15 MB) | Max training data per run |
251
- | `USE_LIGHT_DATASETS` | `0` | Restrict to small/fast datasets only |
252
-
253
- ### EWC (Continual Learning)
254
-
255
- | Variable | CI Default | Description |
256
- |:---|:---|:---|
257
- | `USE_EWC` | `1` | Enable Elastic Weight Consolidation |
258
- | `EWC_LAMBDA` | `500.0` | EWC regularization strength |
259
- | `EWC_SAMPLES` | `5` | Batches used to estimate Fisher matrix |
260
- | `SKIP_FISHER` | `0` | Skip Fisher computation (disables EWC next run) |
261
- | `FREE_OPTIMIZER_BEFORE_FISHER` | `1` | Free optimizer RAM before Fisher computation |
262
- | `FISHER_SEQ_LEN` | `64` | Sequence length used during Fisher estimation |
263
- | `FISHER_THRESHOLD` | `1e-6` | Drop Fisher entries below this value |
264
-
265
- ### Paths & Misc
266
-
267
- | Variable | Default | Description |
268
- |:---|:---|:---|
269
- | `CHECKPOINT_PATH` | `./checkpoint` | Local checkpoint directory |
270
- | `TOKENIZER_ID` | `Qwen/Qwen2.5-0.5B` | HuggingFace tokenizer ID |
271
- | `FAST_MODE` | `0` | Minimal config for quick local debugging |
272
- | `SMOKE_TEST` | `0` | Run tiny in-memory architecture test |
273
- | `GC_EVERY_STEPS` | `5` | Python GC frequency (steps) |
274
- | `DEBUG_STEPS` | `0` | Print verbose per-step debug info |
275
- | `COMET_API_KEY` | *(unset)* | Comet ML experiment tracking key |
276
-
277
- ---
278
-
279
- ## CI/CD Training Pipeline
280
-
281
- ```
282
- Every hour (GitHub Actions cron: '0 * * * *')
283
- β”‚
284
- β”œβ”€β”€ Pull checkpoint from HuggingFace Hub
285
- β”‚ meridianal/FinAI β†’ ./checkpoint/
286
- β”‚
287
- β”œβ”€β”€ Train (timeout: 90 minutes)
288
- β”‚ β€’ Load Qwen2.5-0.5B (or resume checkpoint)
289
- β”‚ β€’ Stream finance datasets (weighted curriculum mix)
290
- β”‚ β€’ 150 AdaFactor steps with gradient checkpointing
291
- β”‚ β€’ EWC regularization (prevent forgetting)
292
- β”‚ β€’ Auto-throttle sequence length if RAM > 12.5 GB
293
- β”‚ β€’ Emergency save + exit if RAM > 14.5 GB
294
- β”‚
295
- β”œβ”€β”€ Upload checkpoint to HuggingFace Hub
296
- β”‚ ./checkpoint/ β†’ meridianal/FinAI/checkpoint/
297
- β”‚
298
- └── Sync dataset state to git
299
- dataset_state.json β†’ main branch
300
- ```
301
-
302
- ### Failure Handling
303
- If training encounters >50 `[ERROR]` lines or any fatal pattern (OOM, NaN explosion), the CI workflow automatically opens a GitHub Issue with the error details and a diagnostic checklist.
304
-
305
- ### Triggering a Manual Run
306
- From the GitHub Actions tab, click **Meridian.AI Train** β†’ **Run workflow**. You can override `MAX_STEPS` at dispatch time.
307
-
308
- ### Force Reset (Nuke & Seed)
309
- To wipe the HuggingFace checkpoint and restart training from a fresh Qwen2.5-0.5B:
310
-
311
- Run workflow with **force_seed: true**. This runs `scripts/seed_hf_repo.py` before training.
312
-
313
- ---
314
-
315
- ## Dataset Curriculum
316
-
317
- Training data is a weighted mix of finance-focused HuggingFace datasets, streamed in real-time (no full downloads):
318
-
319
- | Dataset | Weight | Focus |
320
- |:---|:---|:---|
321
- | `gbharti/finance-alpaca` | 30% | Financial Q&A instructions |
322
- | `nvidia/OpenMathInstruct-2` | 25% | Math reasoning (critical for quantitative finance) |
323
- | `HuggingFaceFW/fineweb-edu` | 20% | General knowledge foundation |
324
- | `FinanceMTEB/financial_phrasebank` | 1% | Sentiment classification |
325
- | `FinanceMTEB/FinQA` | 1% | Financial QA pairs |
326
- | `FinanceMTEB/TATQA` | 1% | Table-and-text QA |
327
- | `FinanceMTEB/FOMC` | 0.8% | FOMC meeting transcripts |
328
- | Various FinanceMTEB | ~20% | Sentiment, ESG, fraud, FLS, events, and more |
329
-
330
- All text is formatted into the `### Instruction: / ### Response:` template before tokenization.
331
-
332
- See [docs/training_pipeline.md](docs/training_pipeline.md) for full dataset details.
333
-
334
- ---
335
-
336
- ## Repository Structure
337
-
338
- ```
339
- FinAI/
340
- β”œβ”€β”€ meridian/
341
- β”‚ β”œβ”€β”€ model/
342
- β”‚ β”‚ β”œβ”€β”€ configuration.py # MeridianConfig (HF PretrainedConfig)
343
- β”‚ β”‚ └── modeling.py # Full model: RMSNorm, RoPE, GQA, SwiGLU, SMoE
344
- β”‚ β”œβ”€β”€ data/
345
- β”‚ β”‚ └── pipeline.py # Streaming dataset curriculum + DataLoader
346
- β”‚ └── training/
347
- β”‚ β”œβ”€β”€ trainer.py # MeridianTrainer (AdaFactor, EWC, RAM guards)
348
- β”‚ └── ewc.py # Elastic Weight Consolidation
349
- β”‚
350
- β”œβ”€β”€ scripts/
351
- β”‚ β”œβ”€β”€ seed_hf_repo.py # Nuke & reseed HuggingFace repo
352
- β”‚ β”œβ”€β”€ evaluate_model.py # Evaluation utilities
353
- β”‚ β”œβ”€β”€ hf_download_and_test.py # Download checkpoint and run test generation
354
- β”‚ └── count_params.py # Parameter counting utility
355
- β”‚
356
- β”œβ”€β”€ docs/
357
- β”‚ β”œβ”€β”€ architecture.md # Detailed architecture specification
358
- β”‚ β”œβ”€β”€ training_pipeline.md # Pipeline, env vars, memory management
359
- β”‚ β”œβ”€β”€ setup_and_usage.md # Setup guide and inference examples
360
- β”‚ └── examples/
361
- β”‚ β”œβ”€β”€ 01_inference.py # HuggingFace inference example
362
- β”‚ β”œβ”€β”€ 02_dataset_pipeline.py # Dataset streaming walkthrough
363
- β”‚ └── 03_model_config.py # Direct architecture instantiation
364
- β”‚
365
- β”œβ”€β”€ tests/
366
- β”‚ β”œβ”€β”€ test_model.py # Architecture unit tests
367
- β”‚ └── test_training.py # Trainer and EWC tests
368
- β”‚
369
- β”œβ”€β”€ .github/
370
- β”‚ └── workflows/
371
- β”‚ β”œβ”€β”€ train.yml # Hourly training CI
372
- β”‚ β”œβ”€β”€ lint.yml # Ruff + Black linting
373
- β”‚ └── dependency-cache.yml
374
- β”‚
375
- β”œβ”€β”€ train.py # Main training entry point
376
- β”œβ”€β”€ requirements.txt # Python dependencies
377
- └── pyproject.toml # Ruff + Black + mypy config
378
- ```
379
-
380
- ---
381
-
382
- ## Troubleshooting
383
-
384
- ### `trust_remote_code=True` warning
385
- Meridian.AI uses a custom model architecture registered with HuggingFace. Passing `trust_remote_code=True` is required when loading with `AutoModelForCausalLM`. This is safe β€” it executes code from the repo you explicitly specify.
386
-
387
- ### `OOM / RuntimeError: [enforce fail]` during training
388
- Reduce memory usage:
389
- ```bash
390
- BATCH_SIZE=1 GRAD_ACCUM=8 BLOCK_SIZE=128 SOFT_RAM_GB=10.0 python train.py
391
- ```
392
-
393
- ### Checkpoint architecture mismatch warning
394
- If you see `[WARN] Checkpoint architecture mismatch (old model)`, the saved `config.json` has `model_type` that doesn't match Qwen2/Llama. The checkpoint will be discarded and training restarts from the base model. This is expected when switching base architectures.
395
-
396
- ### EWC shape mismatch warning
397
- `[WARN] EWC: Dropped N params due to shape/name mismatch` appears when the model architecture changed between runs. EWC state for mismatched layers is safely dropped; valid parameters are kept. Training continues normally.
398
-
399
- ### NaN loss
400
- Usually caused by extreme learning rates or corrupted data batches. The trainer automatically skips batches with NaN loss or NaN gradients. If persistent, try:
401
- ```bash
402
- LEARNING_RATE=1e-5 USE_EWC=0 python train.py
403
- ```
404
-
405
- ### Slow training on CPU
406
- Expected β€” these are CPU-only GitHub runners. With `BATCH_SIZE=1 BLOCK_SIZE=256 MAX_STEPS=150`, expect ~30–60 minutes per run. This fits the 90-minute CI timeout.
407
-
408
- ---
409
-
410
- ## Contributing
411
-
412
- 1. Run the test suite before submitting: `pytest tests/ -v`
413
- 2. Format with black: `black .`
414
- 3. Lint with ruff: `ruff check . --fix`
415
- 4. Keep all code pure Python β€” no unnecessary system dependencies
416
- 5. Submit PRs against `main` with clear commit messages following conventional commits format
417
-
418
- ---
419
-
420
- ## Disclaimer
421
-
422
- Meridian.AI is an experimental research project on continual learning for financial NLP. All model outputs are strictly for academic and research purposes. **Nothing generated by this model constitutes financial advice. Do not use outputs to make real financial decisions or execute trades.**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Meridian.AI β€” Continual-Learning Finance LLM
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
4
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
5
+ [![Base Model](https://img.shields.io/badge/Base-Qwen2.5--0.5B-success.svg)](https://huggingface.co/Qwen/Qwen2.5-0.5B)
6
+ [![Training](https://img.shields.io/badge/Training-Hourly_CI-orange.svg)](https://github.com/MeridianAlgo/FinAI/actions)
7
+ [![HuggingFace](https://img.shields.io/badge/HuggingFace-meridianal%2FFinAI-yellow.svg)](https://huggingface.co/meridianal/FinAI)
8
+ [![Version](https://img.shields.io/badge/version-6.0.0-blueviolet.svg)]()
9
+
10
+ Meridian.AI is a finance-specialized language model that trains itself continuously, every hour, entirely on free GitHub Actions infrastructure. It continuously fine-tunes a **Qwen2.5-0.5B** backbone on 25+ finance and math datasets using **Elastic Weight Consolidation (EWC)** to prevent catastrophic forgetting across training sessions.
11
+
12
+ **Model checkpoints:** [huggingface.co/meridianal/FinAI](https://huggingface.co/meridianal/FinAI)
13
+
14
+ > **What this is, clearly:** Qwen2.5-0.5B (a 494M-parameter causal LM from Alibaba) continuously fine-tuned on finance data via hourly GitHub Actions CI. The `meridian/` module in this repo contains a custom Sparse MoE research architecture used for experiments and smoke tests β€” it is **not** what is deployed in the HuggingFace checkpoint.
15
+
16
+ ---
17
+
18
+ ## Table of Contents
19
+
20
+ - [Why Meridian.AI](#why-meridianai)
21
+ - [Key Design Decisions](#key-design-decisions)
22
+ - [Model Specifications](#model-specifications)
23
+ - [Quick Start](#quick-start)
24
+ - [Inference](#inference)
25
+ - [Local Training](#local-training)
26
+ - [Environment Variables Reference](#environment-variables-reference)
27
+ - [CI/CD Training Pipeline](#cicd-training-pipeline)
28
+ - [Dataset Curriculum](#dataset-curriculum)
29
+ - [Repository Structure](#repository-structure)
30
+ - [Troubleshooting](#troubleshooting)
31
+ - [Changelog](#changelog)
32
+ - [Disclaimer](#disclaimer)
33
+
34
+ ---
35
+
36
+ ## Why Meridian.AI
37
+
38
+ Standard LLMs have a static knowledge cutoff. For finance β€” where earnings reports, Fed decisions, and market conditions change daily β€” this is a critical limitation.
39
+
40
+ Meridian.AI solves this with an **automated continuous training pipeline**: every hour, GitHub Actions pulls the latest checkpoint from HuggingFace, trains on fresh financial data, and pushes the updated checkpoint back. No GPUs. No cloud bills. No manual intervention.
41
+
42
+ Key constraints this design respects:
43
+ - **16 GB RAM** ceiling of free GitHub Actions ubuntu-latest runners
44
+ - **2000 CI minutes/month** free tier (public repos: unlimited)
45
+ - **No persistent storage** between runs β€” all state is round-tripped through HuggingFace Hub
46
+
47
+ ---
48
+
49
+ ## Key Design Decisions
50
+
51
+ ### 1. Qwen2.5-0.5B as Training Backbone
52
+ Rather than training a model from scratch, Meridian.AI continuously fine-tunes `Qwen/Qwen2.5-0.5B` β€” a production-quality base model with strong pre-training on code, math, and multilingual text. This gives the model strong priors out of the box, allowing hourly fine-tuning to specialize it without training from zero.
53
+
54
+ ### 2. Elastic Weight Consolidation (EWC)
55
+ After each hourly training run, the model computes the diagonal Fisher Information Matrix β€” a measure of which parameters were most important for tasks learned so far. The next run adds a regularization penalty for changing those parameters. This prevents the model from "forgetting" financial knowledge from earlier training sessions while absorbing new data.
56
+
57
+ ### 3. Memory-Safe CPU Training
58
+ Every component is designed around the 16 GB RAM constraint:
59
+ - **AdaFactor** optimizer: eliminates the 2Γ—-parameter-size optimizer state of Adam
60
+ - **Gradient checkpointing**: trades compute for activation memory
61
+ - **Soft RAM throttle**: dynamically truncates sequence length when memory pressure rises
62
+ - **Hard RAM guard**: emergency checkpoint + clean exit before OOM
63
+ - **Fisher threshold pruning**: only stores EWC state for parameters with Fisher value above threshold
64
+
65
+ ### 4. Custom Research Architecture (meridian/)
66
+ The `meridian/` module contains a from-scratch Sparse Mixture-of-Experts Transformer (`MeridianForCausalLM`) with:
67
+ - SMoE (8 experts, top-2 per token) on alternating layers
68
+ - Grouped Query Attention (12 Q heads, 4 KV heads)
69
+ - RoPE position embeddings (theta=500,000)
70
+ - SwiGLU feed-forward blocks
71
+ - Financial Numeracy Encoding
72
+
73
+ This module is used for smoke tests and architecture experiments. It is **not** the model in the HuggingFace checkpoint β€” the deployed model is Qwen2.5-0.5B fine-tuned via `AutoModelForCausalLM`.
74
+
75
+ ---
76
+
77
+ ## Model Specifications
78
+
79
+ ### Deployed Checkpoint (HuggingFace)
80
+
81
+ | Specification | Value |
82
+ |:---|:---|
83
+ | Base Model | Qwen2.5-0.5B |
84
+ | Architecture | Qwen2ForCausalLM |
85
+ | Parameters | ~494M |
86
+ | Layers | 24 |
87
+ | Hidden Size | 896 |
88
+ | Attention Heads | 14 Q / 2 KV (GQA) |
89
+ | Vocabulary | 151,643 tokens |
90
+ | Context Window | 32,768 tokens (Qwen2.5 default) |
91
+ | Training dtype | bfloat16 |
92
+ | Continual Learning | Elastic Weight Consolidation (EWC) |
93
+
94
+ ### Research Architecture (meridian/)
95
+
96
+ | Specification | Value |
97
+ |:---|:---|
98
+ | Architecture | Sparse MoE Transformer |
99
+ | Layers | 14 (alternating Dense ↔ MoE) |
100
+ | Attention | GQA: 12 Q heads, 4 KV heads |
101
+ | Position Encoding | RoPE (theta=500,000) |
102
+ | Feed-Forward | SwiGLU |
103
+ | Normalization | RMSNorm |
104
+ | MoE Experts | 8 per layer, top-2 active per token |
105
+ | Vocabulary | 151,665 tokens (Qwen2.5 tokenizer) |
106
+ | Context Window | 2,048 tokens (configurable) |
107
+ | Continual Learning | Elastic Weight Consolidation |
108
+
109
+ ---
110
+
111
+ ## Quick Start
112
+
113
+ ### Prerequisites
114
+ - Python 3.10+
115
+ - ~2 GB disk (for model weights)
116
+
117
+ ### Installation
118
+
119
+ ```bash
120
+ git clone https://github.com/MeridianAlgo/FinAI.git
121
+ cd FinAI
122
+ pip install -r requirements.txt
123
+ ```
124
+
125
+ ### Verify Installation (Smoke Test)
126
+
127
+ Runs a tiny in-memory model to confirm the custom architecture works without downloading anything:
128
+
129
+ ```bash
130
+ SMOKE_TEST=1 FAST_MODE=1 python train.py
131
+ ```
132
+
133
+ Expected output: `[OK] Smoke test passed!`
134
+
135
+ ---
136
+
137
+ ## Inference
138
+
139
+ ### From HuggingFace Hub
140
+
141
+ ```python
142
+ import torch
143
+ from transformers import AutoModelForCausalLM, AutoTokenizer
144
+
145
+ repo_id = "meridianal/FinAI"
146
+ subfolder = "checkpoint"
147
+
148
+ tokenizer = AutoTokenizer.from_pretrained(repo_id, subfolder=subfolder)
149
+ model = AutoModelForCausalLM.from_pretrained(
150
+ repo_id,
151
+ subfolder=subfolder,
152
+ torch_dtype=torch.float32,
153
+ low_cpu_mem_usage=True,
154
+ )
155
+ model.eval()
156
+
157
+ prompt = """### Instruction:
158
+ Explain the difference between a bond's yield to maturity and its coupon rate.
159
+
160
+ ### Response:
161
+ """
162
+
163
+ inputs = tokenizer(prompt, return_tensors="pt")
164
+
165
+ with torch.no_grad():
166
+ output = model.generate(
167
+ **inputs,
168
+ max_new_tokens=200,
169
+ do_sample=True,
170
+ temperature=0.8,
171
+ top_p=0.92,
172
+ repetition_penalty=1.3,
173
+ no_repeat_ngram_size=3,
174
+ pad_token_id=tokenizer.pad_token_id,
175
+ eos_token_id=tokenizer.eos_token_id,
176
+ )
177
+
178
+ print(tokenizer.decode(output[0], skip_special_tokens=True))
179
+ ```
180
+
181
+ > **Note:** `trust_remote_code=True` is **not required** for the deployed checkpoint β€” it is a standard Qwen2 model and loads with `AutoModelForCausalLM` directly.
182
+
183
+ ### From Local Checkpoint
184
+
185
+ Download the checkpoint and run locally:
186
+
187
+ ```bash
188
+ python scripts/download_and_save_hf.py
189
+ ```
190
+
191
+ Then:
192
+
193
+ ```python
194
+ from transformers import AutoModelForCausalLM, AutoTokenizer
195
+
196
+ tokenizer = AutoTokenizer.from_pretrained("./checkpoint")
197
+ model = AutoModelForCausalLM.from_pretrained("./checkpoint")
198
+ ```
199
+
200
+ See [examples/01_inference.py](examples/01_inference.py) for a complete, annotated script.
201
+
202
+ ---
203
+
204
+ ## Local Training
205
+
206
+ ### Full Training Run
207
+
208
+ ```bash
209
+ export HF_TOKEN=your_huggingface_token
210
+ python train.py
211
+ ```
212
+
213
+ The script will:
214
+ 1. Pull the latest checkpoint from HuggingFace (if `HF_TOKEN` is set)
215
+ 2. Load the Qwen2.5-0.5B base model (or resume from checkpoint)
216
+ 3. Stream finance datasets and train for `MAX_STEPS` steps
217
+ 4. Save checkpoint locally (and upload if token is present)
218
+
219
+ ### Fast Debugging Mode
220
+
221
+ Runs with minimal settings (no dataset streaming, 5 steps, tiny sequences):
222
+
223
+ ```bash
224
+ FAST_MODE=1 python train.py
225
+ ```
226
+
227
+ ### Custom Step Count
228
+
229
+ ```bash
230
+ MAX_STEPS=300 BATCH_SIZE=1 python train.py
231
+ ```
232
+
233
+ ### Evaluate Model Quality
234
+
235
+ Compare your checkpoint against base Qwen2.5-0.5B:
236
+
237
+ ```bash
238
+ python scripts/evaluate_model.py
239
+ ```
240
+
241
+ ---
242
+
243
+ ## Environment Variables Reference
244
+
245
+ All variables are optional. CI defaults are shown in `.github/workflows/train.yml`.
246
+
247
+ ### Core Training
248
+
249
+ | Variable | CI Default (v6) | Description |
250
+ |:---|:---|:---|
251
+ | `MAX_STEPS` | `150` | Gradient update steps per run |
252
+ | `TOTAL_STEPS` | `100000` | Cumulative steps across all runs (for LR schedule) |
253
+ | `BATCH_SIZE` | `1` | Samples per micro-step |
254
+ | `GRAD_ACCUM` | `4` | Micro-steps before each optimizer update |
255
+ | `LEARNING_RATE` | `5e-5` | Peak learning rate |
256
+ | `BLOCK_SIZE` | `512` | Token sequence length |
257
+ | `DTYPE` | `bfloat16` | Model dtype (`bfloat16` or `float32`) |
258
+ | `OPTIMIZER` | `adafactor` | Optimizer (`adafactor` or `adamw`) |
259
+
260
+ ### Memory Management
261
+
262
+ | Variable | CI Default | Description |
263
+ |:---|:---|:---|
264
+ | `HARD_RAM_GUARD` | `1` | Enable emergency save + stop at RAM ceiling |
265
+ | `MAX_RAM_GB` | `14.5` | Hard RAM limit in GB |
266
+ | `SOFT_RAM_GB` | `12.5` | Soft limit β€” begins sequence truncation |
267
+ | `SOFT_RAM_PCT` | `80` | Soft limit as % of total RAM |
268
+ | `MIN_THROTTLE_SEQ_LEN` | `64` | Minimum sequence length during throttle |
269
+ | `GRADIENT_CHECKPOINTING` | `1` | Trade compute for activation memory |
270
+ | `SKIP_OPTIMIZER_SAVE` | `1` | Omit optimizer state from checkpoint |
271
+
272
+ ### Dataset
273
+
274
+ | Variable | CI Default | Description |
275
+ |:---|:---|:---|
276
+ | `MAX_BYTES` | `26214400` (25 MB) | Max training data per run |
277
+ | `USE_LIGHT_DATASETS` | `0` | Restrict to small/fast datasets only |
278
+
279
+ ### EWC (Continual Learning)
280
+
281
+ | Variable | CI Default (v6) | Description |
282
+ |:---|:---|:---|
283
+ | `USE_EWC` | `1` | Enable Elastic Weight Consolidation |
284
+ | `EWC_LAMBDA` | `75.0` | EWC regularization strength (reduced from 500) |
285
+ | `EWC_SAMPLES` | `20` | Batches used to estimate Fisher matrix (increased from 5) |
286
+ | `SKIP_FISHER` | `0` | Skip Fisher computation (disables EWC next run) |
287
+ | `FREE_OPTIMIZER_BEFORE_FISHER` | `1` | Free optimizer RAM before Fisher computation |
288
+ | `FISHER_SEQ_LEN` | `64` | Sequence length used during Fisher estimation |
289
+ | `FISHER_THRESHOLD` | `5e-4` | Drop Fisher entries below this value (raised from 1e-4 to reduce EWC file size) |
290
+
291
+ ### Paths & Misc
292
+
293
+ | Variable | Default | Description |
294
+ |:---|:---|:---|
295
+ | `CHECKPOINT_PATH` | `./checkpoint` | Local checkpoint directory |
296
+ | `TOKENIZER_ID` | `Qwen/Qwen2.5-0.5B` | HuggingFace tokenizer ID |
297
+ | `FAST_MODE` | `0` | Minimal config for quick local debugging |
298
+ | `SMOKE_TEST` | `0` | Run tiny in-memory architecture test |
299
+ | `GC_EVERY_STEPS` | `5` | Python GC frequency (steps) |
300
+ | `DEBUG_STEPS` | `0` | Print verbose per-step debug info |
301
+ | `COMET_API_KEY` | *(unset)* | Comet ML experiment tracking key |
302
+
303
+ ---
304
+
305
+ ## CI/CD Training Pipeline
306
+
307
+ ```
308
+ Every hour (GitHub Actions cron: '0 * * * *')
309
+ β”‚
310
+ β”œβ”€β”€ Pull checkpoint from HuggingFace Hub
311
+ β”‚ meridianal/FinAI β†’ ./checkpoint/
312
+ β”‚
313
+ β”œβ”€β”€ Train (timeout: 90 minutes)
314
+ β”‚ β€’ Load Qwen2.5-0.5B (or resume checkpoint)
315
+ β”‚ β€’ Stream finance datasets (25+ sources, weighted curriculum mix)
316
+ β”‚ β€’ 150 AdaFactor steps with gradient checkpointing
317
+ β”‚ β€’ EWC regularization (lambda=75, 20 Fisher samples)
318
+ β”‚ β€’ Auto-throttle sequence length if RAM > 12.5 GB
319
+ β”‚ β€’ Emergency save + exit if RAM > 14.5 GB
320
+ β”‚
321
+ β”œβ”€β”€ Upload checkpoint to HuggingFace Hub
322
+ β”‚ ./checkpoint/ β†’ meridianal/FinAI/checkpoint/
323
+ β”‚
324
+ └── Sync dataset state to git
325
+ dataset_state.json β†’ main branch
326
+ ```
327
+
328
+ ### Failure Handling
329
+ If training encounters >50 `[ERROR]` lines or any fatal pattern (OOM, NaN explosion), the CI workflow automatically opens a GitHub Issue with the error details and a diagnostic checklist.
330
+
331
+ ### Triggering a Manual Run
332
+ From the GitHub Actions tab, click **Meridian.AI Train** β†’ **Run workflow**. You can override `MAX_STEPS` at dispatch time.
333
+
334
+ ### Force Reset (Nuke & Seed)
335
+ To wipe the HuggingFace checkpoint and restart training from a fresh Qwen2.5-0.5B:
336
+
337
+ Run workflow with **force_seed: true**. This runs `scripts/seed_hf_repo.py` before training.
338
+
339
+ ---
340
+
341
+ ## Dataset Curriculum
342
+
343
+ Training data is a weighted mix of finance-focused HuggingFace datasets, streamed in real-time (no full downloads):
344
+
345
+ | Dataset | Weight | Focus |
346
+ |:---|:---|:---|
347
+ | `gbharti/finance-alpaca` | 26% | Financial Q&A instructions |
348
+ | `sujet-ai/Sujet-Finance-Instruct-177k` | 18% | High-quality finance instruction pairs |
349
+ | `nvidia/OpenMathInstruct-2` | 15% | Math reasoning (quantitative finance) |
350
+ | `HuggingFaceFW/fineweb-edu` | 12% | General knowledge foundation |
351
+ | `mhenrichsen/alpaca_data_cleaned` | 5% | General instruction format |
352
+ | `FinGPT/fingpt-sentiment-train` | 4% | Financial news sentiment |
353
+ | `FinanceMTEB/financial_phrasebank` | 1% | Sentiment classification |
354
+ | `FinanceMTEB/FinQA` | 1% | Financial QA pairs |
355
+ | `FinanceMTEB/TATQA` | 1% | Table-and-text QA |
356
+ | `FinanceMTEB/FOMC` | 0.8% | FOMC meeting transcripts |
357
+ | Various FinanceMTEB | ~16% | Sentiment, ESG, fraud, FLS, events, and more |
358
+
359
+ All text is formatted into the `### Instruction: / ### Response:` template before tokenization.
360
+
361
+ See [docs/training_pipeline.md](docs/training_pipeline.md) for full dataset details.
362
+
363
+ ---
364
+
365
+ ## Repository Structure
366
+
367
+ ```
368
+ FinAI/
369
+ β”œβ”€β”€ meridian/ # Python package
370
+ β”‚ β”œβ”€β”€ model/
371
+ β”‚ β”‚ β”œβ”€β”€ configuration.py # MeridianConfig β€” research arch config
372
+ β”‚ β”‚ └── modeling.py # MeridianForCausalLM β€” custom SMoE (research only)
373
+ β”‚ β”œβ”€β”€ data/
374
+ β”‚ β”‚ └── pipeline.py # Streaming dataset curriculum + DataLoader
375
+ β”‚ └── training/
376
+ β”‚ β”œβ”€β”€ trainer.py # MeridianTrainer (AdaFactor, EWC, RAM guards)
377
+ β”‚ └── ewc.py # Elastic Weight Consolidation
378
+ β”‚
379
+ β”œβ”€β”€ scripts/
380
+ β”‚ β”œβ”€β”€ seed_hf_repo.py # Nuke & reseed HuggingFace repo
381
+ β”‚ β”œβ”€β”€ migrate_legacy_and_seed.py # Copy checkpoint β†’ legacy/ and seed fresh model
382
+ β”‚ β”œβ”€β”€ cleanup_hf_checkpoint.py # Remove stale pytorch_model.bin from HF
383
+ β”‚ β”œβ”€β”€ evaluate_model.py # Evaluation: perplexity + generation quality
384
+ β”‚ β”œβ”€β”€ diagnose_and_test.py # Full diagnostic report (download + test)
385
+ β”‚ β”œβ”€β”€ download_and_save_hf.py # Download checkpoint to local directory
386
+ β”‚ β”œβ”€β”€ hf_download_and_test.py # Download + quick generation test
387
+ β”‚ └── count_params.py # Parameter counting utility
388
+ β”‚
389
+ β”œβ”€β”€ examples/
390
+ β”‚ β”œβ”€β”€ 01_inference.py # HuggingFace inference example
391
+ β”‚ β”œβ”€β”€ 02_dataset_pipeline.py # Dataset streaming walkthrough
392
+ β”‚ └── 03_model_config.py # Custom arch instantiation
393
+ β”‚
394
+ β”œβ”€β”€ docs/
395
+ β”‚ β”œβ”€β”€ architecture.md # Detailed architecture spec (custom SMoE)
396
+ β”‚ β”œβ”€β”€ training_pipeline.md # Pipeline, env vars, memory management
397
+ β”‚ └── setup_and_usage.md # Setup guide and inference examples
398
+ β”‚
399
+ β”œβ”€β”€ tests/
400
+ β”‚ β”œβ”€β”€ test_model.py # Architecture unit tests
401
+ β”‚ └── test_training.py # Trainer and EWC tests
402
+ β”‚
403
+ β”œβ”€β”€ .github/
404
+ β”‚ └── workflows/
405
+ β”‚ β”œβ”€β”€ train.yml # Hourly training CI
406
+ β”‚ β”œβ”€β”€ lint.yml # Ruff + Black linting
407
+ β”‚ └── dependency-cache.yml
408
+ β”‚
409
+ β”œβ”€β”€ train.py # Main training entry point
410
+ β”œβ”€β”€ CHANGELOG.md # Version history and training audit
411
+ β”œβ”€β”€ requirements.txt # Python dependencies
412
+ └── pyproject.toml # Ruff + Black + mypy config
413
+ ```
414
+
415
+ ---
416
+
417
+ ## Troubleshooting
418
+
419
+ ### OOM / RuntimeError during training
420
+ Reduce memory usage:
421
+ ```bash
422
+ BATCH_SIZE=1 GRAD_ACCUM=4 BLOCK_SIZE=256 SOFT_RAM_GB=10.0 python train.py
423
+ ```
424
+
425
+ ### Checkpoint architecture mismatch warning
426
+ If you see `[WARN] Checkpoint architecture mismatch (old model)`, the saved `config.json` has a `model_type` that doesn't match `qwen2`. The checkpoint will be discarded and training restarts from the base model. This is expected when switching base architectures.
427
+
428
+ ### EWC shape mismatch warning
429
+ `[WARN] EWC: Dropped N params due to shape/name mismatch` appears when the model architecture changed between runs. EWC state for mismatched layers is safely dropped. Training continues normally.
430
+
431
+ ### NaN loss
432
+ Usually caused by extreme learning rates or corrupted data batches. The trainer automatically skips batches with NaN loss or NaN gradients. If persistent:
433
+ ```bash
434
+ LEARNING_RATE=1e-5 USE_EWC=0 python train.py
435
+ ```
436
+
437
+ ### EWC state file is very large (>500 MB)
438
+ Raise the Fisher threshold to prune more aggressively:
439
+ ```bash
440
+ FISHER_THRESHOLD=1e-3 python train.py
441
+ ```
442
+
443
+ ### Slow training on CPU
444
+ Expected β€” these are CPU-only runners. With `BATCH_SIZE=1 BLOCK_SIZE=512 MAX_STEPS=200`, expect ~50–80 minutes per run. This fits the 90-minute CI timeout.
445
+
446
+ ---
447
+
448
+ ## Contributing
449
+
450
+ 1. Run the test suite before submitting: `pytest tests/ -v`
451
+ 2. Format with black: `black .`
452
+ 3. Lint with ruff: `ruff check . --fix`
453
+ 4. Keep all code pure Python β€” no unnecessary system dependencies
454
+ 5. Submit PRs against `main` with clear commit messages (conventional commits format)
455
+
456
+ ---
457
+
458
+ ## Changelog
459
+
460
+ See [CHANGELOG.md](CHANGELOG.md) for the full version history, training audit, and issue tracker.
461
+
462
+ ---
463
+
464
+ ## Disclaimer
465
+
466
+ Meridian.AI is an experimental research project on continual learning for financial NLP. All model outputs are strictly for academic and research purposes. **Nothing generated by this model constitutes financial advice. Do not use outputs to make real financial decisions or execute trades.**