Faaz commited on
Commit
07de2d7
·
1 Parent(s): 672896a

Add project context doc and WebSight batch uploader

Browse files
Files changed (2) hide show
  1. context.md +573 -0
  2. scripts/upload_websight_images.py +131 -0
context.md ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MINDI 1.5 Vision-Coder — Complete Project Context
2
+
3
+ > **Last updated:** April 16, 2026
4
+ > **Purpose:** This file contains ALL context needed to continue development with any AI assistant.
5
+ > It covers architecture decisions, errors encountered, fixes applied, training state, and exact next steps.
6
+
7
+ ---
8
+
9
+ ## 1. PROJECT OVERVIEW
10
+
11
+ **MINDI 1.5 Vision-Coder** is a multimodal AI model that generates frontend code (HTML/CSS/JS, Next.js, Tailwind) from UI screenshots and text prompts. It combines:
12
+
13
+ - **Qwen/Qwen2.5-Coder-7B-Instruct** — 7.62B param base LLM (Apache 2.0)
14
+ - **CLIP ViT-L/14** — Frozen vision encoder for UI screenshot understanding
15
+ - **LoRA adapters** — Efficient fine-tuning (r=64, alpha=128)
16
+ - **Vision-Language Fusion** — Prepend visual tokens to text embeddings
17
+ - **22 MINDI Special Tokens** — Structured agentic reasoning (think, code, critique, fix, etc.)
18
+ - **3-Phase Training Strategy** — Progressive training on MI300X 192GB
19
+
20
+ **Repos:**
21
+ - **GitHub:** `https://github.com/Faaz345/MINDI-1.5-Vision-Coder.git` (branch: `master`)
22
+ - **HuggingFace Model:** `Mindigenous/MINDI-1.5-Vision-Coder` (private, push as `master:main`)
23
+ - **HuggingFace Dataset:** `Mindigenous/MINDI-1.5-training-data` (private)
24
+ - **HF Token:** Set as `HF_TOKEN` environment variable (stored separately, not in repo)
25
+
26
+ ---
27
+
28
+ ## 2. DIRECTORY STRUCTURE
29
+
30
+ ```
31
+ MINDI-1.5-Vision-Coder/
32
+ ├── src/
33
+ │ ├── model/
34
+ │ │ ├── architecture.py # Qwen2.5-Coder + LoRA wrapper (NOT nn.Module)
35
+ │ │ ├── mindi_model.py # MINDI15 main class (nn.Module)
36
+ │ │ ├── vision_encoder.py # CLIP ViT-L/14 (frozen) + trainable projection
37
+ │ │ ├── fusion_layer.py # VisionLanguageFusion with text_gate
38
+ │ │ └── __init__.py
39
+ │ ├── training/
40
+ │ │ ├── mindi_trainer.py # MINDITrainer: 3-phase loop, streaming data
41
+ │ │ ├── data_pipeline.py # Data processing pipeline
42
+ │ │ └── __init__.py
43
+ │ ├── agents/ # Agentic pipeline (orchestrator, error fixer, UI critic)
44
+ │ ├── inference/ # Generation pipeline
45
+ │ ├── evaluation/ # Evaluation framework
46
+ │ ├── search/ # Tavily search agent
47
+ │ ├── sandbox/ # E2B/Docker code execution
48
+ │ ├── tokenizer/ # MINDI tokenizer wrapper
49
+ │ └── utils/ # Config & env loaders
50
+ ├── scripts/
51
+ │ ├── train.py # Master training launcher (--dry_run, --phase, --resume)
52
+ │ ├── download_websight.py # Download WebSight v0.2 from HF
53
+ │ ├── upload_websight_images.py # Upload images to HF in batches (10K/dir limit)
54
+ │ ├── gpu_diagnostic.py # 6-stage GPU test for MI300X
55
+ │ └── ... (data processing scripts)
56
+ ├── configs/
57
+ │ ├── training_config.yaml # Training hyperparameters
58
+ │ ├── model_config.yaml # Model architecture config
59
+ │ ├── data_config.yaml # Data sources and processing
60
+ │ └── search_config.yaml # Tavily search settings
61
+ ├── data/
62
+ │ ├── processed/ # Text training data (train.jsonl, val.jsonl, test.jsonl)
63
+ │ ├── websight/ # Vision data (52,500 images in subdirs + JSONL)
64
+ │ │ ├── train.jsonl # 50,000 vision-code pairs
65
+ │ │ ├── val.jsonl # 2,500 vision-code pairs
66
+ │ │ └── images/
67
+ │ │ ├── 00/ # ws_0000000.jpg - ws_0009999.jpg (10K each)
68
+ │ │ ├── 01/
69
+ │ │ ├── 02/
70
+ │ │ ├── 03/
71
+ │ │ ├── 04/
72
+ │ │ └── 05/ # ws_0050000.jpg - ws_0052499.jpg (2,500)
73
+ │ ├── tokenizer/
74
+ │ │ ├── mindi_tokenizer/ # Custom tokenizer (vocab 151,685)
75
+ │ │ └── base_tokenizer/ # Original Qwen tokenizer
76
+ │ └── raw/ # Raw downloaded data sources
77
+ ├── api/ # FastAPI endpoints
78
+ ├── checkpoints/ # Model checkpoints
79
+ ├── logs/ # Training logs
80
+ ├── requirements.txt # Full requirements
81
+ ├── requirements-training.txt # Lean MI300X Docker requirements
82
+ ├── setup_mi300x.sh # MI300X Docker setup script
83
+ ├── .gitattributes # LFS tracking for large tokenizer files
84
+ └── .gitignore
85
+ ```
86
+
87
+ ---
88
+
89
+ ## 3. ARCHITECTURE DETAILS
90
+
91
+ ### 3.1 Model Components
92
+
93
+ | Component | Class | File | Params | Trainable |
94
+ |-----------|-------|------|--------|-----------|
95
+ | Base LLM | `MINDIArchitecture` | `architecture.py` | 7.62B | No (frozen) |
96
+ | LoRA | via PEFT | `architecture.py` | 161.5M | Yes |
97
+ | CLIP Vision | `VisionEncoder` | `vision_encoder.py` | 304M | 4.2M (projection only) |
98
+ | Fusion | `VisionLanguageFusion` | `fusion_layer.py` | 16.8M | Yes |
99
+ | **Total** | `MINDI15` | `mindi_model.py` | **8.1B** | **182.5M (2.25%)** |
100
+
101
+ ### 3.2 CRITICAL Architecture Notes
102
+
103
+ 1. **`MINDIArchitecture` is NOT an `nn.Module`** — it's a plain Python wrapper class. The actual trainable PeftModel is accessed via `self.architecture.get_model()` and registered as `self.llm` in `MINDI15.__init__()`.
104
+
105
+ 2. **`self.llm = self.architecture.get_model()`** — This line in `mindi_model.py` registers the PeftModel as a proper submodule so `model.parameters()` can find LoRA params. Without this, the optimizer gets zero trainable parameters.
106
+
107
+ 3. **Vision encoder uses `float32` projection** — CLIP backbone is frozen, only `self.projection` (Linear 1024→4096) trains. The projection operates in float32 for stability even though the rest is bf16.
108
+
109
+ 4. **Fusion layer has `text_gate`** — A learnable scalar parameter (init=0) that creates a residual path for text-only inputs. This ensures gradients flow to the fusion layer during Phase 2 even when processing text-only batches (which have no vision tokens and would otherwise be pure passthrough with no gradient).
110
+
111
+ ### 3.3 Forward Pass Flow
112
+
113
+ ```
114
+ Image → CLIP (frozen) → 256 patches (1024) → projection (4096) → visual_tokens
115
+ Text → tokenizer → input_ids → LLM embedding layer → text_embeds
116
+
117
+ With image: fusion = [gated_visual_tokens; text_embeds] (prepend)
118
+ Without image: fusion = text_embeds + sigmoid(text_gate) * (transformed - text_embeds)
119
+
120
+ fusion → LLM layers (with LoRA) → logits → loss (cross-entropy, labels=-100 for padding)
121
+ ```
122
+
123
+ ### 3.4 LoRA Configuration
124
+
125
+ ```python
126
+ LoraConfig(
127
+ r=64,
128
+ lora_alpha=128,
129
+ lora_dropout=0.05,
130
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
131
+ bias="none",
132
+ task_type=TaskType.CAUSAL_LM,
133
+ )
134
+ ```
135
+
136
+ ### 3.5 MINDI Special Tokens (22 total, 11 pairs)
137
+
138
+ ```
139
+ <|think_start|> / <|think_end|> — Internal reasoning
140
+ <|code_start|> / <|code_end|> — Generated code blocks
141
+ <|file_start|> / <|file_end|> — File references
142
+ <|critique_start|> / <|critique_end|> — Self-critique
143
+ <|suggest_start|> / <|suggest_end|> — Suggestions
144
+ <|search_start|> / <|search_end|> — Search context
145
+ <|error_start|> / <|error_end|> — Error messages
146
+ <|fix_start|> / <|fix_end|> — Fix attempts
147
+ <|vision_start|> / <|vision_end|> — Vision input markers
148
+ <|sandbox_start|> / <|sandbox_end|> — Sandbox execution
149
+ <|context_start|> / <|context_end|> — Context block
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 4. TRAINING PIPELINE
155
+
156
+ ### 4.1 Three-Phase Training Strategy
157
+
158
+ | Phase | Name | Steps | LR | Batch | Components | Data | Purpose |
159
+ |-------|------|-------|-----|-------|-----------|------|---------|
160
+ | 1 | `phase1_lora` | 5,000 | 2e-4 | 16 | LoRA only | Text-only code | Teach coding patterns |
161
+ | 2 | `phase2_vision_bridge` | 2,500 | 1e-5 | 8 | Vision+Fusion | WebSight images | Align visual tokens |
162
+ | 3 | `phase3_all` | 2,500 | 5e-5 | 12 | All trainable | Mixed text+vision | Joint fine-tuning |
163
+
164
+ **Total: 10,000 steps**
165
+
166
+ ### 4.2 Training Data
167
+
168
+ **Text data (Phase 1 + Phase 3):**
169
+ - `data/processed/train.jsonl` — 1,304,486 examples, 4.18 GB
170
+ - `data/processed/val.jsonl` — 72,471 examples
171
+ - Sources: CodeAlpaca, CodeFeedback, EvolCode, MagicCoder, StarCoder (5 langs), Synthetic Next.js
172
+
173
+ **Vision data (Phase 2 + Phase 3):**
174
+ - `data/websight/train.jsonl` — 50,000 image+code pairs, 114 MB JSONL
175
+ - `data/websight/val.jsonl` — 2,500 image+code pairs, 5.7 MB JSONL
176
+ - `data/websight/images/` — 52,500 JPG screenshots in 6 subdirectories (11.6 GB)
177
+ - Source: HuggingFaceM4/WebSight v0.2 (UI screenshot → HTML/CSS pairs)
178
+
179
+ **WebSight JSONL format:**
180
+ ```json
181
+ {
182
+ "id": "websight_0000001",
183
+ "type": "vision_code",
184
+ "source": "websight_v0.2",
185
+ "image_path": "data/websight/images/00/ws_0000001.jpg",
186
+ "messages": [
187
+ {"role": "system", "content": "You are MINDI 1.5 Vision-Coder..."},
188
+ {"role": "user", "content": "<|vision_start|><|vision_end|>\nGenerate the HTML/CSS code for this UI screenshot."},
189
+ {"role": "assistant", "content": "<|think_start|>...<|think_end|>\n<|code_start|>\n...HTML/CSS...\n<|code_end|>"}
190
+ ],
191
+ "metadata": {"dataset": "websight", "version": "v0.2"}
192
+ }
193
+ ```
194
+
195
+ **IMPORTANT:** Images are organized in subdirectories of ≤10,000 files each because HuggingFace has a 10K files/directory limit. The JSONL `image_path` fields reference the subdirectory structure (e.g., `data/websight/images/00/ws_0000001.jpg`).
196
+
197
+ ### 4.3 Data Loading
198
+
199
+ - **`StreamingJSONLDataset`** (in `mindi_trainer.py`) — Streams from disk line-by-line, tokenizes on-the-fly
200
+ - **Shuffle buffer** of 10,000 examples (reservoir-style)
201
+ - **Image loading** via `_load_image()` — loads PIL images from relative paths
202
+ - **Custom collate function** — stacks tensors, keeps images as a list
203
+ - **Phase routing** — Phase 1 uses text data, Phase 2 uses WebSight, Phase 3 uses text (with inline images if present)
204
+
205
+ ### 4.4 Key Training Features
206
+
207
+ - **bf16 precision** — Required for MI300X stability (NOT fp16)
208
+ - **Gradient checkpointing** — Enabled even with 192GB VRAM
209
+ - **torch.compile()** — Optional, works on ROCm
210
+ - **Cosine LR with warmup** — Per-phase schedules
211
+ - **Gradient accumulation** — Configurable per phase (default: 4)
212
+ - **Emergency checkpoint** — Saved on Ctrl+C
213
+ - **Crash checkpoint** — Saved on unhandled exceptions
214
+
215
+ ---
216
+
217
+ ## 5. TRAINING HISTORY & RESULTS
218
+
219
+ ### 5.1 Phase 1 Dry Run — SUCCESS ✅
220
+
221
+ **Date:** April 15, 2026 (on DigitalOcean MI300X)
222
+ **Command:** `python3 scripts/train.py --dry_run --no_wandb`
223
+ **Result:** Loss dropped from 1.94 → 0.85 in 10 steps, completed in 12.1 minutes
224
+ **VRAM usage:** ~14.3 GB
225
+
226
+ ### 5.2 Phase 2 — First Attempt FAILED ❌
227
+
228
+ **Error:** `element 0 of tensors does not require grad and does not have a grad_fn`
229
+ **Root cause:** Phase 2 trains vision+fusion with LoRA frozen. Text-only data means fusion is pure passthrough (no gradient path). The fusion layer was getting zero gradients because without vision tokens, the text-only path was `return text_embeds, attention_mask` — a pure passthrough with no learnable operation.
230
+ **Fix:** Added `text_gate` learnable residual parameter to `VisionLanguageFusion`. Text-only path changed to: `text_embeds + sigmoid(text_gate) * (transformed - text_embeds)`. Also built the WebSight vision data pipeline to provide actual image+code pairs for Phase 2.
231
+
232
+ ### 5.3 Full 3-Phase Dry Run — NOT YET COMPLETED
233
+
234
+ The MI300X GPU kept hanging/wedging (see Section 6). Phase 2 and 3 with the new WebSight data pipeline have NOT been tested yet.
235
+
236
+ ---
237
+
238
+ ## 6. ERRORS & FIXES — COMPLETE HISTORY
239
+
240
+ ### 6.1 GPU Hang #1 — HSA_OVERRIDE_GFX_VERSION
241
+
242
+ **Symptom:** GPU completely unresponsive. `torch.cuda.get_device_name(0)` returns blank, any CUDA operation hangs.
243
+ **Root cause:** `HSA_OVERRIDE_GFX_VERSION=11.0.0` was set in the Docker container. This conflicts with ROCm 7.0's native MI300X/gfx942 support.
244
+ **Fix:** Do NOT set `HSA_OVERRIDE_GFX_VERSION`. ROCm 7.0 natively supports gfx942. Remove it from all scripts/env.
245
+ **Commit:** `4a33f96 Remove HSA_OVERRIDE_GFX_VERSION`
246
+
247
+ ### 6.2 No Trainable Parameters in Optimizer
248
+
249
+ **Symptom:** `RuntimeError: No trainable parameters in phase 'phase1_lora'`
250
+ **Root cause:** `MINDIArchitecture` is a plain Python class (not `nn.Module`). When `MINDI15` calls `model.parameters()`, it doesn't find the LoRA parameters because the PeftModel isn't registered as a submodule.
251
+ **Fix:** Added `self.llm = self.architecture.get_model()` in `MINDI15.__init__()` to register the PeftModel as a proper nn.Module submodule. Updated `forward()` and `generate()` to use `self.llm` instead of `self.architecture.get_model()`.
252
+ **Commit:** `cdc806e Fix: register LLM as nn.Module submodule so optimizer finds LoRA params`
253
+
254
+ ### 6.3 extra_special_tokens Format Error
255
+
256
+ **Symptom:** `TypeError` when loading tokenizer — transformers 4.55 expects `extra_special_tokens` as a dict, not a list.
257
+ **Fix:** Changed `data/tokenizer/mindi_tokenizer/tokenizer_config.json`: converted `extra_special_tokens` from list format to `{"token_name": {"content": "..."}}` dict format.
258
+ **Commit:** `02eef51 Fix extra_special_tokens: list to dict for transformers 4.55`
259
+
260
+ ### 6.4 Phase 2 Gradient Flow Crash
261
+
262
+ **Symptom:** `element 0 of tensors does not require grad and does not have a grad_fn` during Phase 2
263
+ **Root cause:** Text-only data → no vision tokens → fusion is pure passthrough → no gradient path to fusion parameters.
264
+ **Fix:** (1) Added `text_gate` learnable residual gate in `VisionLanguageFusion` for text-only gradient flow. (2) Built WebSight vision data pipeline with actual image+code pairs.
265
+ **Commit:** `4e9835e Fix Phase 2: fusion layer processes text-only via learnable residual gate`
266
+
267
+ ### 6.5 Git LFS Issues
268
+
269
+ **Symptom:** `tokenizer.json` files >10MB causing push failures to HuggingFace.
270
+ **Fix:** Configured `.gitattributes` for LFS tracking. Ran `git lfs migrate import` to rewrite history. Force-pushed to both GitHub and HF.
271
+ **Commit:** `161c946 Track large tokenizer files with Git LFS`
272
+
273
+ ### 6.6 HuggingFace Auth for MI300X Clone
274
+
275
+ **Symptom:** `git clone` from HF failed with auth error in Docker container.
276
+ **Fix:** Use token as both username and password: `https://hf_TOKEN:hf_TOKEN@huggingface.co/Mindigenous/MINDI-1.5-Vision-Coder.git`
277
+ Also needed: `apt-get install -y git-lfs && git lfs install`
278
+
279
+ ### 6.7 GPU Hang #2 — Driver Wedge After Heavy I/O
280
+
281
+ **Symptom:** After interrupted HF upload + training attempt, GPU shows 100% utilization with 0% VRAM in `rocm-smi`. Even `torch.randn(device='cuda')` hangs. Docker restart insufficient.
282
+ **Kernel log:** `amdgpu: GPU reset begin!` → `device wedged, but recovered through reset` → But GPU% stays at 100%.
283
+ **Fix:**
284
+ 1. `docker stop rocm`
285
+ 2. `echo 1 > /sys/bus/pci/devices/0000:83:00.0/reset` (PCI address from `lspci | grep AMD`)
286
+ 3. If GPU% still 100%: `modprobe -r amdgpu && modprobe amdgpu`
287
+ 4. Verify `rocm-smi` shows GPU% = 0% before restarting Docker
288
+ **Status:** Droplet was deleted. Will need to handle this on fresh droplet if it recurs.
289
+
290
+ ### 6.8 HuggingFace Upload Limits
291
+
292
+ **Symptom:** `413 Payload Too Large` (25K files/commit) and `400 Bad Request` (10K files/directory)
293
+ **Fix:** Reorganized 52,500 images into 6 subdirectories of ≤10K files (`00/` through `05/`). Upload in separate commits per subdirectory. Updated JSONL `image_path` fields to include subdirectory.
294
+ **Script:** `scripts/upload_websight_images.py`
295
+
296
+ ---
297
+
298
+ ## 7. MI300X DEPLOYMENT
299
+
300
+ ### 7.1 Infrastructure
301
+
302
+ - **Provider:** DigitalOcean GPU Droplet
303
+ - **GPU:** AMD Instinct MI300X (192GB HBM3 VRAM)
304
+ - **Cost:** $1.99/hr
305
+ - **Docker container:** Named `rocm`, accessed via `docker exec -it rocm /bin/bash`
306
+ - **ROCm/HIP:** 7.0.51831-a3e329ad8
307
+ - **PyTorch:** 2.9.0.dev20250821+rocm7.0.0
308
+ - **Python:** 3.10
309
+
310
+ ### 7.2 Critical Environment Variables
311
+
312
+ ```bash
313
+ export HF_TOKEN=<your-hf-token> # Get from HF settings page
314
+ export HF_HUB_DISABLE_PROGRESS_BARS=1
315
+ export PYTORCH_ROCM_ARCH=gfx942
316
+ # DO NOT SET: HSA_OVERRIDE_GFX_VERSION (causes GPU hang on ROCm 7.0)
317
+ ```
318
+
319
+ ### 7.3 Fresh Droplet Setup Procedure
320
+
321
+ ```bash
322
+ # 1. SSH into droplet
323
+ ssh root@<DROPLET_IP>
324
+
325
+ # 2. Start Docker
326
+ docker start rocm
327
+ docker exec -it rocm /bin/bash
328
+
329
+ # 3. Set environment (inside Docker)
330
+ export HF_TOKEN=<your-hf-token> # Get from HF settings page
331
+ export HF_HUB_DISABLE_PROGRESS_BARS=1
332
+ export PYTORCH_ROCM_ARCH=gfx942
333
+
334
+ # 4. Quick GPU test
335
+ python3 -c "import torch; print('GPU:', torch.cuda.get_device_name(0)); x=torch.randn(100,device='cuda'); print('OK:', x.sum().item())"
336
+
337
+ # 5. Install git-lfs
338
+ apt-get update && apt-get install -y git-lfs
339
+ git lfs install
340
+
341
+ # 6. Clone code repo
342
+ cd /workspace
343
+ git clone https://$HF_TOKEN:$HF_TOKEN@huggingface.co/Mindigenous/MINDI-1.5-Vision-Coder.git
344
+ cd MINDI-1.5-Vision-Coder
345
+
346
+ # 7. Install requirements
347
+ pip install -r requirements-training.txt
348
+
349
+ # 8. Download training data from HF dataset repo
350
+ python3 -c "
351
+ from huggingface_hub import snapshot_download
352
+ import os
353
+ # HF_TOKEN must be set in environment
354
+ snapshot_download(
355
+ repo_id='Mindigenous/MINDI-1.5-training-data',
356
+ repo_type='dataset',
357
+ local_dir='data',
358
+ token=os.environ['HF_TOKEN'],
359
+ )
360
+ print('Data download complete!')
361
+ "
362
+
363
+ # 9. Verify data
364
+ ls -la data/processed/
365
+ ls -la data/websight/
366
+ ls data/websight/images/ | head
367
+
368
+ # 10. Run GPU diagnostic
369
+ python3 scripts/gpu_diagnostic.py
370
+
371
+ # 11. Dry run
372
+ python3 scripts/train.py --dry_run --no_wandb
373
+
374
+ # 12. Full training
375
+ python3 scripts/train.py --no_wandb
376
+ ```
377
+
378
+ ### 7.4 GPU Hang Recovery (if it happens again)
379
+
380
+ ```bash
381
+ # From HOST (not inside Docker):
382
+ docker stop rocm
383
+ echo 1 > /sys/bus/pci/devices/0000:83:00.0/reset # PCI address may differ
384
+ rocm-smi # Verify GPU% = 0%
385
+ # If still 100%:
386
+ modprobe -r amdgpu && modprobe amdgpu
387
+ rocm-smi # Should show 0% now
388
+ docker start rocm
389
+ ```
390
+
391
+ ---
392
+
393
+ ## 8. HF DATASET REPO STRUCTURE
394
+
395
+ **Repo:** `Mindigenous/MINDI-1.5-training-data` (private, type: dataset)
396
+
397
+ ```
398
+ ├── .gitattributes
399
+ ├── README.md
400
+ ├── processed/
401
+ │ ├── train.jsonl # 1.3M text examples
402
+ │ ├── val.jsonl
403
+ │ ├── test.jsonl
404
+ │ ├── filter_report.json
405
+ │ ├── mindi_filtered.jsonl
406
+ │ └── split_meta.json
407
+ ├── raw/ # Original data sources (11 files)
408
+ ├── tokenizer/
409
+ │ ├── base_tokenizer/
410
+ │ └── mindi_tokenizer/
411
+ └── websight/
412
+ ├── train.jsonl # 50K vision-code JSONL
413
+ ├── val.jsonl # 2.5K vision-code JSONL
414
+ └── images/
415
+ ├── 00/ # 10,000 JPGs
416
+ ├── 01/ # 10,000 JPGs
417
+ ├── 02/ # 10,000 JPGs
418
+ ├── 03/ # 10,000 JPGs
419
+ ├── 04/ # 10,000 JPGs (uploading as of April 16)
420
+ └── 05/ # 2,500 JPGs (uploading as of April 16)
421
+ ```
422
+
423
+ **NOTE:** As of April 16, 2026, subdirectories 00-03 are uploaded. 04 and 05 are being uploaded via `scripts/upload_websight_images.py`. If upload was interrupted, re-run the script — it skips already-uploaded subdirs.
424
+
425
+ ---
426
+
427
+ ## 9. GIT HISTORY (CHRONOLOGICAL)
428
+
429
+ ```
430
+ 553fbf7 feat: initial project scaffold for MINDI 1.5 Vision-Coder
431
+ 11e0d89 Day 1 Complete: Tokenizer setup — 22 MINDI special tokens (vocab 151,685)
432
+ 59c6c97 Day 2 COMPLETE: 1.48M examples processed, 6GB dataset, WebSight done
433
+ 2ff5c54 Day 3 COMPLETE: Full model architecture (7 files)
434
+ 1c36b28 Fix train.py: mem -> memory on line 225
435
+ f04f58b Fix setup_mi300x.sh step 2 + add project context summary
436
+ 35fd5fc Fix setup_mi300x.sh for Docker container on MI300X droplet
437
+ 5fb9ec3 Add GPU diagnostic script, fix architecture loading with sync
438
+ 161c946 Track large tokenizer files with Git LFS
439
+ 4a33f96 Remove HSA_OVERRIDE_GFX_VERSION - ROCm 7.0 native MI300X support
440
+ 24b5fb1 Add requirements-training.txt for MI300X Docker
441
+ 02eef51 Fix extra_special_tokens: list to dict for transformers 4.55
442
+ cdc806e Fix: register LLM as nn.Module submodule so optimizer finds LoRA params
443
+ 4e9835e Fix Phase 2: fusion layer text_gate for gradient flow
444
+ 672896a Add WebSight vision data pipeline: download, image-aware loader, phase routing
445
+ ```
446
+
447
+ ---
448
+
449
+ ## 10. WHAT WORKS (VERIFIED) ✅
450
+
451
+ 1. **Tokenizer** — 151,685 vocab with 22 MINDI special tokens, loads correctly
452
+ 2. **Model initialization** — MINDI15 loads all 4 components, 182.5M trainable params
453
+ 3. **GPU diagnostic** — All 6 tests pass (bf16 matmul, 1GB alloc, CPU→CUDA transfer, forward pass)
454
+ 4. **Phase 1 dry run** — Loss 1.94 → 0.85 in 10 steps ✅
455
+ 5. **WebSight download** — 52,500 images (11.6 GB) downloaded and organized
456
+ 6. **Data format** — JSONL with image_path references, streaming dataset works
457
+ 7. **Git LFS** — Large tokenizer files tracked correctly
458
+ 8. **Code pushed** — All code on GitHub master + HF model repo main
459
+
460
+ ---
461
+
462
+ ## 11. WHAT REMAINS (TODO) ❌
463
+
464
+ 1. **Complete WebSight upload to HF** — Subdirs 04 and 05 still uploading (re-run `scripts/upload_websight_images.py` if interrupted)
465
+ 2. **Full 3-phase dry run** — Phase 2 (WebSight) and Phase 3 (mixed) NOT yet tested with the vision pipeline
466
+ 3. **Full production training** — 10,000 steps total (Phase 1: 5K, Phase 2: 2.5K, Phase 3: 2.5K)
467
+ 4. **Inference testing** — Generate code from screenshots after training
468
+ 5. **Commit `upload_websight_images.py` and `context.md`** — These new files need to be pushed
469
+
470
+ ---
471
+
472
+ ## 12. KNOWN ISSUES & GOTCHAS
473
+
474
+ ### DO NOT:
475
+ - Set `HSA_OVERRIDE_GFX_VERSION=11.0.0` — kills GPU on ROCm 7.0
476
+ - Use `fp16` on MI300X — use `bf16` for stability
477
+ - Try to upload >10K files to a single HF directory — split into subdirs
478
+ - Try to commit >25K files in a single HF commit — batch commits
479
+ - Use the global Python (base env) on Windows — use venv (global torch DLL is broken)
480
+
481
+ ### WATCH OUT FOR:
482
+ - GPU hanging after heavy I/O — check `rocm-smi` shows 0% GPU before training
483
+ - Data paths — WebSight images use **relative paths** from project root in JSONL
484
+ - `MINDIArchitecture` is NOT `nn.Module` — always use `self.llm` inside MINDI15
485
+ - The `text_gate` in fusion starts at 0 (sigmoid=0.5) — this is intentional
486
+ - On MI300X, Docker container named `rocm` — always `docker exec -it rocm /bin/bash`
487
+
488
+ ---
489
+
490
+ ## 13. COMMANDS REFERENCE
491
+
492
+ ### Local (Windows, PowerShell, in venv):
493
+ ```powershell
494
+ # Activate venv
495
+ & ".\venv\Scripts\Activate.ps1"
496
+
497
+ # Download WebSight
498
+ $env:HF_TOKEN="<your-hf-token>"
499
+ python scripts/download_websight.py --num_train 50000 --num_val 2500
500
+
501
+ # Upload WebSight images to HF (handles subdirs, retry, skip)
502
+ python scripts/upload_websight_images.py
503
+
504
+ # Push code to GitHub + HF
505
+ git push origin master
506
+ git push hf master:main
507
+ ```
508
+
509
+ ### MI300X (Linux, Docker, inside container):
510
+ ```bash
511
+ # Dry run (10 steps per phase)
512
+ python3 scripts/train.py --dry_run --no_wandb
513
+
514
+ # Full training
515
+ python3 scripts/train.py --no_wandb
516
+
517
+ # Single phase
518
+ python3 scripts/train.py --phase 1 --no_wandb
519
+ python3 scripts/train.py --phase 2 --no_wandb
520
+ python3 scripts/train.py --phase 3 --no_wandb
521
+
522
+ # Resume from checkpoint
523
+ python3 scripts/train.py --resume checkpoints/training/phase1_lora_step5000 --no_wandb
524
+
525
+ # GPU diagnostic
526
+ python3 scripts/gpu_diagnostic.py
527
+ ```
528
+
529
+ ---
530
+
531
+ ## 14. NEXT SESSION CHECKLIST
532
+
533
+ When continuing with a new AI assistant:
534
+
535
+ 1. **Open this directory** in your IDE
536
+ 2. **Read this file first** to get full context
537
+ 3. **Check WebSight upload status:**
538
+ ```powershell
539
+ python -c "import os; from huggingface_hub import HfApi; api=HfApi(token=os.environ['HF_TOKEN']); files=[f for f in api.list_repo_files('Mindigenous/MINDI-1.5-training-data', repo_type='dataset') if 'websight/images' in f]; print(f'{len(files)} images in HF repo')"
540
+ ```
541
+ 4. If <52,500: re-run `python scripts/upload_websight_images.py`
542
+ 5. **Push any uncommitted files:**
543
+ ```bash
544
+ git add scripts/upload_websight_images.py context.md
545
+ git commit -m "Add WebSight batch uploader and project context"
546
+ git push origin master
547
+ git push hf master:main
548
+ ```
549
+ 6. **Spin up fresh MI300X droplet** on DigitalOcean
550
+ 7. **Follow Section 7.3** for setup procedure
551
+ 8. **Run dry run first** to verify all 3 phases work
552
+ 9. **Then full training** — `python3 scripts/train.py --no_wandb`
553
+
554
+ ---
555
+
556
+ ## 15. DATA FILE LOCATIONS ON HF DATASET REPO
557
+
558
+ When cloning data on MI300X using `snapshot_download`, files will land at:
559
+
560
+ | HF Repo Path | Local Path (relative to project root) |
561
+ |---|---|
562
+ | `processed/train.jsonl` | `data/processed/train.jsonl` |
563
+ | `processed/val.jsonl` | `data/processed/val.jsonl` |
564
+ | `websight/train.jsonl` | `data/websight/train.jsonl` |
565
+ | `websight/val.jsonl` | `data/websight/val.jsonl` |
566
+ | `websight/images/00/*.jpg` | `data/websight/images/00/*.jpg` |
567
+ | `tokenizer/mindi_tokenizer/*` | `data/tokenizer/mindi_tokenizer/*` |
568
+
569
+ The `snapshot_download(local_dir='data')` call places everything correctly because the HF repo structure mirrors the local `data/` directory.
570
+
571
+ ---
572
+
573
+ *This context file was created on April 16, 2026 during Claude Opus 4.6 session to ensure project continuity.*
scripts/upload_websight_images.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Reorganize WebSight images into subdirectories (HF 10K files/dir limit)
4
+ and update JSONL paths, then upload in batches.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import shutil
10
+ from pathlib import Path
11
+ from huggingface_hub import HfApi
12
+
13
+ TOKEN = os.environ["HF_TOKEN"] # set HF_TOKEN env var before running
14
+ REPO_ID = "Mindigenous/MINDI-1.5-training-data"
15
+ IMAGES_DIR = Path("data/websight/images")
16
+ FILES_PER_DIR = 10000 # max files per directory on HF
17
+
18
+ # Step 1: Reorganize images into subdirectories
19
+ print("=" * 60)
20
+ print(" Step 1: Reorganizing images into subdirectories")
21
+ print("=" * 60)
22
+
23
+ all_images = sorted(IMAGES_DIR.glob("*.jpg"))
24
+ print(f"Found {len(all_images)} images in flat directory")
25
+
26
+ if not all_images:
27
+ # Check if already reorganized
28
+ subdirs = sorted([d for d in IMAGES_DIR.iterdir() if d.is_dir()])
29
+ if subdirs:
30
+ total = sum(len(list(d.glob("*.jpg"))) for d in subdirs)
31
+ print(f"Already reorganized into {len(subdirs)} subdirs with {total} total images")
32
+ else:
33
+ print("ERROR: No images found!")
34
+ exit(1)
35
+ else:
36
+ for i, img in enumerate(all_images):
37
+ subdir_idx = i // FILES_PER_DIR
38
+ subdir = IMAGES_DIR / f"{subdir_idx:02d}"
39
+ subdir.mkdir(exist_ok=True)
40
+ shutil.move(str(img), str(subdir / img.name))
41
+ if (i + 1) % 10000 == 0:
42
+ print(f" Moved {i + 1:,} images...")
43
+
44
+ subdirs = sorted([d for d in IMAGES_DIR.iterdir() if d.is_dir()])
45
+ for sd in subdirs:
46
+ count = len(list(sd.glob("*.jpg")))
47
+ print(f" {sd.name}/: {count:,} images")
48
+
49
+ # Step 2: Update JSONL files with new paths
50
+ print(f"\n{'=' * 60}")
51
+ print(" Step 2: Updating JSONL paths")
52
+ print("=" * 60)
53
+
54
+ for jsonl_name in ["train.jsonl", "val.jsonl"]:
55
+ jsonl_path = Path("data/websight") / jsonl_name
56
+ if not jsonl_path.exists():
57
+ print(f" {jsonl_name}: not found, skipping")
58
+ continue
59
+
60
+ lines = jsonl_path.read_text(encoding="utf-8").strip().split("\n")
61
+ updated = []
62
+ for line in lines:
63
+ entry = json.loads(line)
64
+ old_path = entry["image_path"]
65
+ filename = os.path.basename(old_path)
66
+ num = int(filename.replace("ws_", "").replace(".jpg", ""))
67
+ subdir_idx = num // FILES_PER_DIR
68
+ new_path = f"data/websight/images/{subdir_idx:02d}/{filename}"
69
+ entry["image_path"] = new_path
70
+ updated.append(json.dumps(entry, ensure_ascii=False))
71
+
72
+ jsonl_path.write_text("\n".join(updated) + "\n", encoding="utf-8")
73
+ print(f" {jsonl_name}: updated {len(updated):,} entries")
74
+
75
+ # Step 3: Upload to HF
76
+ print(f"\n{'=' * 60}")
77
+ print(" Step 3: Uploading to HuggingFace")
78
+ print("=" * 60)
79
+
80
+ api = HfApi(token=TOKEN)
81
+
82
+ # Upload updated JSONL files first
83
+ print("\nUploading updated JSONL files...")
84
+ for jsonl_name in ["train.jsonl", "val.jsonl"]:
85
+ jsonl_path = Path("data/websight") / jsonl_name
86
+ api.upload_file(
87
+ path_or_fileobj=str(jsonl_path),
88
+ path_in_repo=f"websight/{jsonl_name}",
89
+ repo_id=REPO_ID,
90
+ repo_type="dataset",
91
+ )
92
+ print(f" {jsonl_name} uploaded")
93
+
94
+ # Check which subdirs are already uploaded
95
+ import time
96
+ repo_files = set(api.list_repo_files(REPO_ID, repo_type="dataset"))
97
+
98
+ # Upload each subdirectory separately
99
+ subdirs = sorted([d for d in IMAGES_DIR.iterdir() if d.is_dir()])
100
+ for i, subdir in enumerate(subdirs):
101
+ count = len(list(subdir.glob("*.jpg")))
102
+ # Check if this subdir is already fully uploaded
103
+ sample_file = f"websight/images/{subdir.name}/{sorted(subdir.glob('*.jpg'))[0].name}"
104
+ if sample_file in repo_files:
105
+ print(f"\nSubdir {subdir.name}/ ({count:,} images) [{i+1}/{len(subdirs)}] — already uploaded, skipping.")
106
+ continue
107
+
108
+ for attempt in range(3):
109
+ try:
110
+ print(f"\nUploading subdir {subdir.name}/ ({count:,} images) [{i+1}/{len(subdirs)}] (attempt {attempt+1})...")
111
+ api.upload_folder(
112
+ folder_path=str(subdir),
113
+ path_in_repo=f"websight/images/{subdir.name}",
114
+ repo_id=REPO_ID,
115
+ repo_type="dataset",
116
+ commit_message=f"Add WebSight images subdir {subdir.name} ({count} images)",
117
+ )
118
+ print(f" Subdir {subdir.name} committed!")
119
+ break
120
+ except Exception as e:
121
+ print(f" Error: {e}")
122
+ if attempt < 2:
123
+ wait = 30 * (attempt + 1)
124
+ print(f" Retrying in {wait}s...")
125
+ time.sleep(wait)
126
+ else:
127
+ print(f" FAILED after 3 attempts. Run script again to resume.")
128
+
129
+ print(f"\n{'=' * 60}")
130
+ print(" ALL DONE! All WebSight data uploaded to HF.")
131
+ print("=" * 60)