File size: 38,036 Bytes
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7884d5
 
 
 
7c33ebc
 
 
 
 
 
 
 
bb01096
 
 
 
 
 
 
 
 
 
7c33ebc
bb01096
7c33ebc
bb01096
 
 
 
 
 
 
a7884d5
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc94ef
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc94ef
 
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc94ef
7c33ebc
 
fbc94ef
7c33ebc
fbc94ef
 
 
 
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7884d5
bb01096
a7884d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
a7884d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
 
 
a7884d5
 
 
 
 
 
bb01096
 
 
a7884d5
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
 
 
 
 
 
fbc94ef
7c33ebc
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bac741f
 
 
fbc94ef
 
bb01096
 
7c33ebc
bb01096
fbc94ef
bb01096
 
fbc94ef
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bac741f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bac741f
 
 
 
 
 
bb01096
 
 
 
 
bac741f
 
bb01096
bac741f
 
bb01096
 
bac741f
 
 
 
 
bb01096
bac741f
bb01096
bac741f
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc94ef
 
 
 
bb01096
 
7c33ebc
 
 
 
 
bb01096
 
 
 
 
 
 
 
 
7c33ebc
fbc94ef
bb01096
 
 
 
 
fbc94ef
 
bb01096
 
 
fbc94ef
bb01096
 
 
 
 
 
 
fbc94ef
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
a7884d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
 
 
 
bac741f
bb01096
 
 
 
fbc94ef
 
 
 
bb01096
 
 
 
 
 
 
 
 
7c33ebc
bb01096
 
 
 
 
fbc94ef
bb01096
 
 
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
bb01096
7c33ebc
bb01096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
bb01096
 
 
 
 
7c33ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb01096
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
 
 
 
 
bb01096
7c33ebc
 
 
 
 
 
bb01096
 
 
 
 
 
 
fbc94ef
 
 
 
 
bb01096
a7884d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c33ebc
 
 
 
 
 
 
 
 
fbc94ef
7c33ebc
 
 
fbc94ef
 
 
 
 
 
bb01096
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
"""
Train OpticalCompressor on Qwen3-VL-8B for UI-to-Code.

Architecture:
  Qwen3-VL ViT+Merger (frozen) → OpticalCompressor (trainable) → Qwen3 LLM (LoRA)

Usage:
  # Single GPU smoke test
  CUDA_VISIBLE_DEVICES=0 python scripts/train_compressor.py \
      --max_samples 100 --epochs 1 --batch_size 1

  # Full 6-GPU DDP training
  torchrun --nproc_per_node=6 scripts/train_compressor.py \
      --max_samples 50000 --epochs 5 --batch_size 1 --grad_accum 8

  # Resume from checkpoint
  torchrun --nproc_per_node=6 scripts/train_compressor.py \
      --resume checkpoints/optical/latest.pt --epochs 5

  # Mix WebSight + eval-aligned subset (ref_screenshots_websight + websight_gt_html, 100 pairs)
  CUDA_VISIBLE_DEVICES=1 python scripts/train_compressor.py \
      --mix_root data --epochs 10 --max_samples 5000

  # Mix WebSight + Design2Code eval split (484 pairs; run scripts/export_design2code_gt_html.py first)
  CUDA_VISIBLE_DEVICES=1 python scripts/train_compressor.py \
      --mix_root data --mix_images_subdir ref_screenshots --mix_gt_subdir gt_html

  # Per-epoch CLIP eval + continue training later (optimizer in checkpoint; --epochs is final count)
  CUDA_VISIBLE_DEVICES=1 python scripts/train_compressor.py ... --epochs 5 --eval_after_epoch
  CUDA_VISIBLE_DEVICES=1 python scripts/train_compressor.py ... --resume checkpoints/optical/latest.pt --epochs 10
"""

import os
os.environ["HF_ENDPOINT"] = os.environ.get("HF_ENDPOINT", "https://hf-mirror.com")
os.environ["HF_HOME"] = os.environ.get("HF_HOME", "/root/rivermind-data/huggingface")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Suppress NCCL debug noise
os.environ.setdefault("NCCL_DEBUG", "WARN")

import argparse
import gc
import math
import subprocess
import sys
import time
from pathlib import Path

import torch
import torch.nn as nn
import torch.distributed as dist
from torch.utils.data import ConcatDataset, Dataset, DataLoader, DistributedSampler

PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

from models.optical_compressor import OpticalCompressor

# ---------- constants ----------
UI2CODE_PROMPT = (
    "Convert this webpage screenshot to HTML code. "
    "Generate a complete, self-contained HTML file with inline CSS. "
    "Output only the code."
)
IMAGE_TOKEN_ID = 151655  # <|image_pad|> in Qwen3-VL


def log(msg, rank=0):
    """Print only on main process."""
    if int(os.environ.get("LOCAL_RANK", 0)) == rank:
        print(msg, flush=True)


def log_all(msg):
    """Print on all processes (for debugging hangs)."""
    rank = int(os.environ.get("LOCAL_RANK", 0))
    print(f"[rank{rank}] {msg}", flush=True)


def _uipress_stack_to_cpu(model):
    model.base_model.cpu()
    model.compressor.cpu()
    model.lora_modules.cpu()


def _uipress_stack_to_device(model, device):
    model.base_model.to(device)
    model.compressor.to(device)
    model.lora_modules.to(device)


def _run_subprocess_eval_and_clip(args, out_dir: Path, epoch: int) -> Path | None:
    """Free GPU, run eval_all + step_clip_batch; returns method_dir with clip_scores.json or None."""
    eval_root = (
        Path(args.eval_output_dir).resolve()
        if args.eval_output_dir
        else (PROJECT_ROOT / "results" / "clip_per_epoch" / out_dir.name)
    )
    eval_epoch_dir = eval_root / f"epoch_{epoch}"
    eval_epoch_dir.mkdir(parents=True, exist_ok=True)
    run_name = f"uipress_{args.target_tokens}"
    method_dir = eval_epoch_dir / run_name

    cmd_base = [sys.executable, str(PROJECT_ROOT / "scripts" / "eval_all.py")]
    r1 = subprocess.run(
        cmd_base
        + [
            "--method",
            "uipress",
            "--checkpoint",
            str(out_dir / "latest.pt"),
            "--max_samples",
            str(args.eval_max_samples),
            "--data_dir",
            args.eval_data_dir,
            "--output_dir",
            str(eval_epoch_dir),
            "--target_tokens",
            str(args.target_tokens),
        ],
        cwd=str(PROJECT_ROOT),
    )
    if r1.returncode != 0:
        print(f"  [eval] eval_all.py failed rc={r1.returncode}", flush=True)
        return None

    cmd_clip = [
        sys.executable,
        str(PROJECT_ROOT / "scripts" / "step_clip_batch.py"),
        "--method_dir",
        str(method_dir),
        "--ref_dir",
        args.eval_ref_dir,
        "--clip_device",
        args.eval_clip_device,
    ]
    r2 = subprocess.run(cmd_clip, cwd=str(PROJECT_ROOT))
    if r2.returncode != 0:
        print(f"  [eval] step_clip_batch.py failed rc={r2.returncode}", flush=True)
        return None

    clip_path = method_dir / "clip_scores.json"
    if clip_path.exists():
        import json

        summary = json.loads(clip_path.read_text(encoding="utf-8"))
        print(
            f"  [eval] epoch {epoch} CLIP avg={summary.get('avg_clip')} "
            f"n={summary.get('n')} -> {clip_path}",
            flush=True,
        )
    return method_dir


def _torch_load_compat(path, map_location):
    try:
        return torch.load(path, map_location=map_location, weights_only=False)
    except TypeError:
        return torch.load(path, map_location=map_location)


def _rebuild_optimizer_scheduler(args, model, device, total_steps, ckpt_path: Path):
    lora_trainable = [p for p in model.lora_modules.parameters() if p.requires_grad]
    trainable_params = (
        list(model.compressor.parameters())
        + lora_trainable
    )
    optim_groups = [{"params": list(model.compressor.parameters()), "lr": args.lr_compressor}]
    if lora_trainable:
        optim_groups.append({"params": lora_trainable, "lr": args.lr_lora})
    optimizer = torch.optim.AdamW(optim_groups, weight_decay=0.01)
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=max(total_steps, 1), eta_min=1e-6,
    )
    if ckpt_path.exists():
        blob = _torch_load_compat(ckpt_path, map_location=device)
        if isinstance(blob.get("optimizer"), dict):
            try:
                optimizer.load_state_dict(blob["optimizer"])
            except Exception as e:
                print(f"  [warn] optimizer state not loaded: {e}", flush=True)
        if isinstance(blob.get("scheduler"), dict):
            try:
                scheduler.load_state_dict(blob["scheduler"])
            except Exception as e:
                print(f"  [warn] scheduler state not loaded: {e}", flush=True)
    return optimizer, scheduler, trainable_params


# ---------- dataset ----------
class WebSightDataset(Dataset):
    """Loads WebSight screenshot-HTML pairs from local files.

    Supports two formats:
    1. Raw files: data_dir/images/*.png + data_dir/*.html (+ optional metadata.json)
    2. HuggingFace datasets: load_from_disk format
    """

    def __init__(self, data_dir, max_samples=None):
        import json
        from PIL import Image
        data_path = Path(data_dir)

        # Check for metadata JSON first
        json_files = list(data_path.glob("*.json"))
        img_dir = data_path / "images"

        if json_files and img_dir.exists():
            # Format 1: JSON metadata + raw files
            with open(json_files[0], "r") as f:
                metadata = json.load(f)
            self.samples = []
            for item in metadata:
                img_path = data_path / "images" / f"{item['id']}.png"
                html_path = data_path / f"{item['id']}.html"
                if img_path.exists() and html_path.exists():
                    self.samples.append({
                        "image_path": str(img_path),
                        "html_path": str(html_path),
                    })
            self.mode = "files"
        elif img_dir.exists():
            # Format 1b: just images + html, no JSON
            self.samples = []
            for img_path in sorted(img_dir.glob("*.png")):
                html_path = data_path / f"{img_path.stem}.html"
                if html_path.exists():
                    self.samples.append({
                        "image_path": str(img_path),
                        "html_path": str(html_path),
                    })
            self.mode = "files"
        else:
            # Format 2: HuggingFace dataset
            from datasets import load_from_disk
            self.ds = load_from_disk(data_dir)
            if isinstance(self.ds, dict):
                self.ds = self.ds["train"]
            self.mode = "hf"

        if max_samples:
            if self.mode == "files":
                self.samples = self.samples[:max_samples]
            elif self.mode == "hf" and max_samples < len(self.ds):
                self.ds = self.ds.select(range(max_samples))

    def __len__(self):
        if self.mode == "files":
            return len(self.samples)
        return len(self.ds)

    def __getitem__(self, idx):
        from PIL import Image
        if self.mode == "files":
            s = self.samples[idx]
            image = Image.open(s["image_path"]).convert("RGB")
            html = Path(s["html_path"]).read_text(encoding="utf-8", errors="ignore")
            return {"image": image, "html": html}
        else:
            item = self.ds[idx]
            image = item["image"].convert("RGB")
            html = item["code"] if "code" in item else item.get("text", "")
            return {"image": image, "html": html}


class Design2CodeDataset(Dataset):
    """Screenshot + HTML pairs (e.g. eval subset with local GT).

    Layout A — legacy ``data_dir``:
      ``testset_final/*.png`` or ``ref_screenshots/*.png`` + ``gt_html/*.html``
      (falls back to ``websight_gt_html`` if ``gt_html`` is missing).

    Layout B — explicit ``images_dir`` + ``gt_dir`` (recommended for
    ``ref_screenshots_websight`` + ``websight_gt_html``).
    """

    def __init__(
        self,
        data_dir=None,
        max_samples=None,
        *,
        images_dir=None,
        gt_dir=None,
        require_html=True,
    ):
        self.samples = []

        if images_dir is not None and gt_dir is not None:
            img_root = Path(images_dir)
            gt_root = Path(gt_dir)
            if not img_root.is_dir():
                raise FileNotFoundError(f"images_dir not found: {img_root}")
            if not gt_root.is_dir():
                raise FileNotFoundError(f"gt_dir not found: {gt_root}")
            for png in sorted(img_root.glob("*.png")):
                gt_path = gt_root / f"{png.stem}.html"
                if require_html and not gt_path.exists():
                    continue
                self.samples.append({"image_path": png, "html_path": gt_path if gt_path.exists() else None})
                if max_samples and len(self.samples) >= max_samples:
                    break
            return

        if data_dir is None:
            raise ValueError("Design2CodeDataset: pass data_dir or (images_dir, gt_dir)")

        data_path = Path(data_dir)
        img_dir = data_path / "testset_final"
        if not img_dir.exists():
            img_dir = data_path / "ref_screenshots"

        gt_dir_resolved = None
        for name in ("gt_html", "websight_gt_html"):
            d = data_path / name
            if d.is_dir():
                gt_dir_resolved = d
                break

        if img_dir.exists():
            for png in sorted(img_dir.glob("*.png")):
                gt_path = (gt_dir_resolved / f"{png.stem}.html") if gt_dir_resolved else None
                if require_html and (gt_path is None or not gt_path.exists()):
                    continue
                self.samples.append({"image_path": png, "html_path": gt_path})
                if max_samples and len(self.samples) >= max_samples:
                    break

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, idx):
        from PIL import Image
        s = self.samples[idx]
        image = Image.open(s["image_path"]).convert("RGB")
        html = ""
        if s["html_path"] and s["html_path"].exists():
            html = s["html_path"].read_text(encoding="utf-8", errors="ignore")
        return {"image": image, "html": html}


# ---------- LoRA ----------
class LoRALinear(nn.Module):
    """Simple LoRA wrapper for a frozen Linear layer."""

    def __init__(self, base_layer, r=16, alpha=32):
        super().__init__()
        self.base = base_layer
        self.r = r
        self.scale = alpha / r
        in_f = base_layer.in_features
        out_f = base_layer.out_features
        self.lora_a = nn.Linear(in_f, r, bias=False)
        self.lora_b = nn.Linear(r, out_f, bias=False)
        nn.init.kaiming_uniform_(self.lora_a.weight, a=math.sqrt(5))
        nn.init.zeros_(self.lora_b.weight)
        dtype = base_layer.weight.dtype
        self.lora_a = self.lora_a.to(dtype)
        self.lora_b = self.lora_b.to(dtype)

    @property
    def in_features(self):
        return self.base.in_features

    @property
    def out_features(self):
        return self.base.out_features

    @property
    def weight(self):
        return self.base.weight

    def forward(self, x):
        base_out = self.base(x)
        lora_out = self.lora_b(self.lora_a(x)) * self.scale
        return base_out + lora_out


# ---------- model wrapper ----------
class CompressedQwen3VL(nn.Module):
    """
    Qwen3-VL with OpticalCompressor inserted between ViT+Merger and LLM.

    Forward flow:
      1. image → model.visual() → [N, 3584] visual embeds  (frozen)
      2. [N, 3584] → OpticalCompressor → [256, 3584]        (trainable)
      3. Build inputs_embeds with 256 compressed image tokens
      4. Forward through LLM with LoRA                       (LoRA trainable)
      5. Loss on HTML output tokens
    """

    def __init__(
        self,
        model_id,
        target_tokens=256,
        lora_r=16,
        lora_alpha=32,
        max_html_tokens=2048,
        enable_lora=True,
    ):
        super().__init__()
        from transformers import Qwen3VLForConditionalGeneration, AutoProcessor

        self.base_model = Qwen3VLForConditionalGeneration.from_pretrained(
            model_id, trust_remote_code=True, torch_dtype=torch.bfloat16,
        )
        self.processor = AutoProcessor.from_pretrained(
            model_id, trust_remote_code=True,
        )

        llm_hidden = self.base_model.config.text_config.hidden_size  # 3584 for 8B

        # Freeze everything
        for param in self.base_model.parameters():
            param.requires_grad = False

        # Add compressor
        self.compressor = OpticalCompressor(
            hidden_dim=llm_hidden,
            target_tokens=target_tokens,
        ).to(torch.bfloat16)

        # Monkey-patch get_image_features so it auto-compresses visual tokens.
        self._patch_vision(compressor=self.compressor, target_tokens=target_tokens)

        # Add LoRA to LLM decoder (can be disabled for ablation).
        self._add_lora(lora_r, lora_alpha, enable_lora=enable_lora)

        self.target_tokens = target_tokens
        self.max_html_tokens = max_html_tokens

    def _add_lora(self, r, alpha, enable_lora=True):
        """Manually inject LoRA into q_proj, v_proj of each LLM layer."""
        self.lora_modules = nn.ModuleDict()
        if (not enable_lora) or r <= 0:
            return
        lm = self.base_model.model
        if hasattr(lm, "language_model"):
            layers = lm.language_model.layers
        elif hasattr(lm, "layers"):
            layers = lm.layers
        else:
            print("WARNING: Cannot find LLM layers, skipping LoRA")
            return

        for i, layer in enumerate(layers):
            attn = layer.self_attn
            for proj_name in ["q_proj", "v_proj"]:
                orig = getattr(attn, proj_name)
                lora_key = f"layer{i}_{proj_name}"
                self.lora_modules[lora_key] = LoRALinear(
                    orig, r=r, alpha=alpha,
                )
                setattr(attn, proj_name, self.lora_modules[lora_key])

    def _patch_vision(self, compressor, target_tokens):
        """Monkey-patch get_image_features to auto-compress visual tokens.

        The compressed tokens PER IMAGE = target_tokens (not T*H*W/spatial_merge_size^2).
        We intercept get_image_features so Qwen3-VL's M-RoPE / placeholder_mask /
        masked_scatter all work unchanged — only the actual embedding values change.
        """
        import functools

        orig_get_img = self.base_model.model.get_image_features

        @functools.wraps(orig_get_img)
        def patched_get_image_features(pixel_values, image_grid_thw=None, **kwargs):
            import torch
            from transformers.models.qwen3_vl.modeling_qwen3_vl import (
                BaseModelOutputWithDeepstackFeatures,
            )
            vision_output = orig_get_img(pixel_values, image_grid_thw, **kwargs)
            pooler = vision_output.pooler_output
            if not isinstance(pooler, (list, tuple)):
                flat = pooler
            else:
                flat = torch.cat(pooler, dim=0)

            # Compute LLM-side grid after spatial merge
            vis = self.base_model.model.visual
            sms = vis.spatial_merge_size
            grid_llm = image_grid_thw.clone()
            grid_llm[:, 1] = grid_llm[:, 1] // sms
            grid_llm[:, 2] = grid_llm[:, 2] // sms
            num_images = image_grid_thw.shape[0]
            compressed_parts = []
            offset = 0
            for i in range(num_images):
                t, h, w = grid_llm[i].tolist()
                n_orig = t * h * w
                orig_slice = flat[offset: offset + n_orig]
                offset += n_orig
                comp_part, _ = compressor(orig_slice.unsqueeze(0), grid_llm[i:i+1])
                compressed_parts.append(comp_part.squeeze(0))

            compressed_flat = torch.cat(compressed_parts, dim=0)
            split_sizes = [target_tokens] * num_images

            # Reconstruct pooler_output as list (expected by Qwen3VLModel.forward)
            vision_output.pooler_output = torch.split(compressed_flat, split_sizes)
            # Disable deepstack processing to avoid dimension mismatch
            vision_output.deepstack_features = []

            return vision_output

        self.base_model.model.get_image_features = patched_get_image_features

    def prepare_inputs(self, images, htmls):
        """Prepare model inputs for a batch of image-html pairs."""
        batch_messages = []
        for img in images:
            batch_messages.append([{"role": "user", "content": [
                {"type": "image", "image": img},
                {"type": "text", "text": UI2CODE_PROMPT},
            ]}])

        texts = [
            self.processor.apply_chat_template(
                msg, tokenize=False, add_generation_prompt=True,
            )
            for msg in batch_messages
        ]

        inputs = self.processor(
            text=texts, images=images, return_tensors="pt", padding=True,
        )
        return inputs

    def forward(self, images, htmls, device):
        """Full training forward pass. Returns loss scalar.

        The _patch_vision monkey-patch auto-compresses visual tokens inside
        get_image_features, so Qwen3-VL's forward handles M-RoPE, placeholder_mask,
        and masked_scatter automatically. We only supply the HTML teacher targets.
        """
        inputs = self.prepare_inputs(images, htmls)
        pixel_values = inputs["pixel_values"].to(device, torch.bfloat16)
        image_grid_thw = inputs["image_grid_thw"].to(device)
        input_ids = inputs["input_ids"].to(device)

        # Build HTML target (teacher forcing)
        new_input_ids, labels = self._rebuild_sequence(input_ids, htmls, device)

        # Attention mask
        pad_token_id = self.processor.tokenizer.pad_token_id or 0
        attention_mask = (new_input_ids != pad_token_id).long()

        # Forward through Qwen3-VL.
        # input_ids: provides #image tokens for M-RoPE / placeholder_mask.
        # pixel_values + image_grid_thw: trigger patched get_image_features
        #   which returns compressed embeddings → auto masked-scattered.
        # output_hidden_states=False: disables deepstack_features mismatch.
        outputs = self.base_model(
            input_ids=new_input_ids,
            attention_mask=attention_mask,
            pixel_values=pixel_values,
            image_grid_thw=image_grid_thw,
            output_hidden_states=False,
            labels=labels,
        )
        return outputs.loss

    def _rebuild_sequence(self, orig_input_ids, htmls, device):
        """Replace variable-length image tokens with fixed target_tokens placeholders."""
        tokenizer = self.processor.tokenizer
        batch_new_ids = []
        batch_labels = []
        max_len = 0

        for b in range(orig_input_ids.shape[0]):
            ids = orig_input_ids[b].tolist()

            img_positions = [i for i, t in enumerate(ids) if t == IMAGE_TOKEN_ID]

            if img_positions:
                before = ids[:img_positions[0]]
                after = ids[img_positions[-1] + 1:]
            else:
                before = ids
                after = []

            new_ids = before + [IMAGE_TOKEN_ID] * self.target_tokens + after

            html_tokens = tokenizer.encode(
                htmls[b],
                add_special_tokens=False,
                max_length=self.max_html_tokens,
                truncation=True,
            )
            html_tokens.append(tokenizer.eos_token_id)

            full_ids = new_ids + html_tokens
            labels = [-100] * len(new_ids) + html_tokens

            batch_new_ids.append(full_ids)
            batch_labels.append(labels)
            max_len = max(max_len, len(full_ids))

        pad_id = tokenizer.pad_token_id or 0
        for i in range(len(batch_new_ids)):
            pad_len = max_len - len(batch_new_ids[i])
            batch_new_ids[i] += [pad_id] * pad_len
            batch_labels[i] += [-100] * pad_len

        new_input_ids = torch.tensor(batch_new_ids, device=device)
        labels = torch.tensor(batch_labels, device=device)
        return new_input_ids, labels

    def _scatter_visual(self, text_embeds, input_ids, compressed, grid_thw):
        """Replace image placeholder embeddings with compressed visual tokens."""
        inputs_embeds = text_embeds.clone()
        offset = 0
        for b in range(input_ids.shape[0]):
            img_mask = input_ids[b] == IMAGE_TOKEN_ID
            n_img = img_mask.sum().item()
            if n_img > 0 and offset < compressed.shape[0]:
                n_take = min(n_img, compressed.shape[0] - offset)
                img_positions = img_mask.nonzero(as_tuple=True)[0][:n_take]
                inputs_embeds[b, img_positions] = compressed[offset:offset + n_take]
                offset += n_take
        return inputs_embeds

    def _build_position_ids(self, input_ids, grid_thw, device):
        """
        Build 3D position IDs compatible with Qwen3-VL's M-RoPE.
        Vectorized — no Python loops over individual tokens.
        """
        batch_size, seq_len = input_ids.shape
        position_ids = torch.zeros(batch_size, 3, seq_len, dtype=torch.long, device=device)

        for b in range(batch_size):
            ids = input_ids[b]
            img_mask = ids == IMAGE_TOKEN_ID
            text_mask = ~img_mask

            # Text positions before image: sequential
            img_positions = img_mask.nonzero(as_tuple=True)[0]
            text_positions = text_mask.nonzero(as_tuple=True)[0]

            if len(img_positions) == 0:
                # No image tokens — just sequential
                pos = torch.arange(seq_len, device=device)
                position_ids[b, 0] = pos
                position_ids[b, 1] = pos
                position_ids[b, 2] = pos
                continue

            first_img = img_positions[0].item()
            last_img = img_positions[-1].item()

            # Text before image: sequential (same across all 3 dims)
            text_before_mask = text_mask.clone()
            text_before_mask[last_img + 1:] = False
            text_before_positions = text_before_mask.nonzero(as_tuple=True)[0]
            n_text_before = text_before_positions.shape[0]
            if n_text_before > 0:
                seq_vals = torch.arange(n_text_before, device=device)
                position_ids[b, 0, text_before_positions] = seq_vals
                position_ids[b, 1, text_before_positions] = seq_vals
                position_ids[b, 2, text_before_positions] = seq_vals

            text_offset = n_text_before

            # Image positions: 2D grid layout
            t, h, w = grid_thw[b % grid_thw.shape[0]].tolist()
            t, h, w = int(t), int(h), int(w)
            n_img = len(img_positions)

            idx = torch.arange(n_img, device=device)
            hw = h * w
            ti = idx // hw
            hi = (idx % hw) // w
            wi = idx % w

            position_ids[b, 0, img_positions] = text_offset + ti
            position_ids[b, 1, img_positions] = text_offset + hi
            position_ids[b, 2, img_positions] = text_offset + wi

            # Text after image: sequential, offset past image grid
            img_max_pos = text_offset + max(h, w)
            text_after_positions = text_mask[last_img + 1:].nonzero(as_tuple=True)[0] + last_img + 1
            if len(text_after_positions) > 0:
                after_vals = torch.arange(len(text_after_positions), device=device) + img_max_pos + 1
                position_ids[b, 0, text_after_positions] = after_vals
                position_ids[b, 1, text_after_positions] = after_vals
                position_ids[b, 2, text_after_positions] = after_vals

        return position_ids


# ---------- training loop ----------
def train(args):
    # DDP setup
    local_rank = int(os.environ.get("LOCAL_RANK", 0))
    world_size = int(os.environ.get("WORLD_SIZE", 1))
    is_distributed = world_size > 1

    if is_distributed:
        dist.init_process_group("nccl", device_id=torch.device(f"cuda:{local_rank}"))
        torch.cuda.set_device(local_rank)
    device = torch.device(f"cuda:{local_rank}")
    is_main = local_rank == 0

    if is_main:
        print(f"=== UIPress Optical Compressor Training ===", flush=True)
        print(f"  GPUs: {world_size}, target_tokens: {args.target_tokens}", flush=True)
        if args.disable_lora:
            print("  LoRA: disabled", flush=True)
        else:
            print(f"  LoRA r={args.lora_r}, alpha={args.lora_alpha}", flush=True)
        print(f"  Batch: {args.batch_size} x {args.grad_accum} x {world_size} "
              f"= {args.batch_size * args.grad_accum * world_size}", flush=True)
        if args.eval_after_epoch and is_distributed:
            print(
                "  Warning: --eval_after_epoch is disabled under DDP (single-GPU only).",
                flush=True,
            )

    # Load model
    log_all("Loading model...")
    t0 = time.time()
    model = CompressedQwen3VL(
        model_id=args.model_id,
        target_tokens=args.target_tokens,
        lora_r=args.lora_r,
        lora_alpha=args.lora_alpha,
        max_html_tokens=args.max_html_tokens,
        enable_lora=not args.disable_lora,
    )
    model.base_model.to(device)
    model.compressor.to(device)
    log_all(f"Model loaded in {time.time() - t0:.1f}s")

    lora_trainable = [p for p in model.lora_modules.parameters() if p.requires_grad]

    # Count trainable params
    if is_main:
        comp_params = model.compressor.count_parameters()
        lora_params = sum(p.numel() for p in lora_trainable)
        print(f"  Compressor params: {comp_params['trainable']:,}", flush=True)
        print(f"  LoRA params: {lora_params:,}", flush=True)
        print(f"  Total trainable: {comp_params['trainable'] + lora_params:,}", flush=True)

    # Collect all trainable parameters
    trainable_params = (
        list(model.compressor.parameters())
        + lora_trainable
    )

    # No DDP wrapper — LoRA is injected via setattr into base_model,
    # so DDP can't track it. Instead we manually allreduce gradients.
    if is_distributed:
        log_all("Syncing ranks...")
        dist.barrier()
        log_all("Ranks synced")

    # Dataset (load on all ranks — each rank reads from same disk)
    log_all("Loading dataset...")
    t0 = time.time()
    dataset = WebSightDataset(args.data_dir, max_samples=args.max_samples)
    if args.mix_root:
        mix_root = (PROJECT_ROOT / args.mix_root).resolve()
        mix = Design2CodeDataset(
            images_dir=mix_root / args.mix_images_subdir,
            gt_dir=mix_root / args.mix_gt_subdir,
            max_samples=args.mix_max_samples,
            require_html=True,
        )
        if is_main:
            print(f"  Mix split: {len(mix)} pairs from {mix_root / args.mix_images_subdir}", flush=True)
        if len(mix) > 0:
            dataset = ConcatDataset([dataset, mix])
        elif is_main:
            print(
                "  Warning: mix_root set but 0 samples with GT; train on WebSight only. "
                "Check mix_images_subdir / mix_gt_subdir.",
                flush=True,
            )
    log_all(f"Dataset loaded: {len(dataset)} samples in {time.time() - t0:.1f}s")

    sampler = DistributedSampler(dataset) if is_distributed else None
    loader = DataLoader(
        dataset, batch_size=args.batch_size, sampler=sampler,
        shuffle=(sampler is None), num_workers=0, pin_memory=True,
        collate_fn=lambda batch: batch,
    )

    # Optimizer — use trainable_params collected before DDP
    optim_groups = [{"params": list(model.compressor.parameters()), "lr": args.lr_compressor}]
    if lora_trainable:
        optim_groups.append({"params": lora_trainable, "lr": args.lr_lora})
    optimizer = torch.optim.AdamW(optim_groups, weight_decay=0.01)

    total_steps = len(loader) * args.epochs // args.grad_accum
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=max(total_steps, 1), eta_min=1e-6,
    )

    # Resume
    start_epoch = 0
    if args.resume and Path(args.resume).exists():
        ckpt = _torch_load_compat(args.resume, map_location=device)
        comp_state = ckpt.get("compressor", ckpt)
        new_state = {}
        for k, v in comp_state.items():
            new_state[k.replace("module.", "")] = v
        model.compressor.load_state_dict(new_state)
        if "lora" in ckpt and len(model.lora_modules) > 0:
            model.lora_modules.load_state_dict(ckpt["lora"])
        if "epoch" in ckpt:
            start_epoch = ckpt["epoch"] + 1
        if isinstance(ckpt.get("optimizer"), dict):
            try:
                optimizer.load_state_dict(ckpt["optimizer"])
            except Exception as e:
                if is_main:
                    print(f"  [warn] resume: optimizer not restored: {e}", flush=True)
        if isinstance(ckpt.get("scheduler"), dict):
            try:
                scheduler.load_state_dict(ckpt["scheduler"])
            except Exception as e:
                if is_main:
                    print(f"  [warn] resume: scheduler not restored: {e}", flush=True)
        if is_main:
            print(f"  Resumed from {args.resume}, next epoch index {start_epoch}", flush=True)

    # Output dir
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    # Training
    if is_main:
        print(f"\n--- Training starts ---", flush=True)
        print(f"  Steps/epoch: {len(loader)}, total optimizer steps: {total_steps}", flush=True)

    for epoch in range(start_epoch, args.epochs):
        if sampler is not None:
            sampler.set_epoch(epoch)

        model.compressor.train()
        for m in model.lora_modules.values():
            m.train()

        epoch_loss = 0.0
        n_steps = 0
        optimizer.zero_grad()
        t_epoch = time.time()

        for step, batch in enumerate(loader):
            images = [s["image"] for s in batch]
            htmls = [s["html"] for s in batch]

            try:
                t_step = time.time()
                loss = model.forward(images, htmls, device)
                loss = loss / args.grad_accum
                loss.backward()

                epoch_loss += loss.item() * args.grad_accum
                n_steps += 1

                # Print first step immediately + every grad_accum steps
                if is_main and (step == 0 or (step + 1) % args.grad_accum == 0):
                    elapsed = time.time() - t_step
                    avg = epoch_loss / n_steps if n_steps > 0 else 0
                    mem = torch.cuda.max_memory_allocated() / 1024**3
                    print(f"  E{epoch} S{step+1}/{len(loader)} "
                          f"loss={avg:.4f} step_time={elapsed:.1f}s "
                          f"mem={mem:.1f}GB", flush=True)

            except RuntimeError as e:
                if "out of memory" in str(e):
                    log_all(f"OOM at step {step}, skipping")
                    torch.cuda.empty_cache()
                    optimizer.zero_grad()
                    continue
                raise

            if (step + 1) % args.grad_accum == 0:
                # Manual allreduce gradients across GPUs
                if is_distributed:
                    for p in trainable_params:
                        if p.grad is not None:
                            dist.all_reduce(p.grad, op=dist.ReduceOp.AVG)

                torch.nn.utils.clip_grad_norm_(trainable_params, 1.0)
                optimizer.step()
                scheduler.step()
                optimizer.zero_grad()

        avg_loss = epoch_loss / max(n_steps, 1)
        epoch_time = time.time() - t_epoch
        if is_main:
            print(f"  Epoch {epoch}: avg_loss={avg_loss:.4f} time={epoch_time/60:.1f}min", flush=True)
            ckpt = {
                "compressor": model.compressor.state_dict(),
                "lora": model.lora_modules.state_dict(),
                "epoch": epoch,
                "loss": avg_loss,
                "args": vars(args),
                "optimizer": optimizer.state_dict(),
                "scheduler": scheduler.state_dict(),
            }
            torch.save(ckpt, out_dir / f"epoch{epoch}.pt")
            torch.save(ckpt, out_dir / "latest.pt")
            print(f"  Saved checkpoint: {out_dir / f'epoch{epoch}.pt'}", flush=True)

        do_eval = args.eval_after_epoch and (not is_distributed) and is_main
        if do_eval:
            if is_main:
                print(f"  Running post-epoch eval (freeing GPU)...", flush=True)
            _uipress_stack_to_cpu(model)
            gc.collect()
            torch.cuda.empty_cache()
            try:
                _run_subprocess_eval_and_clip(args, out_dir, epoch)
            finally:
                _uipress_stack_to_device(model, device)
            optimizer, scheduler, trainable_params = _rebuild_optimizer_scheduler(
                args, model, device, total_steps, out_dir / "latest.pt",
            )
            if is_main:
                print(f"  Restored optimizer/scheduler from latest.pt", flush=True)

    if is_distributed:
        dist.destroy_process_group()

    if is_main:
        print("\n=== Training complete ===", flush=True)


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--model_id", default="Qwen/Qwen3-VL-8B-Instruct")
    p.add_argument("--data_dir", default="data/websight")
    p.add_argument("--output_dir", default="checkpoints/optical")
    p.add_argument(
        "--max_samples",
        type=int,
        default=10000,
        help="Cap WebSight training pairs (lower = much faster epochs).",
    )
    p.add_argument("--epochs", type=int, default=5)
    p.add_argument(
        "--max_html_tokens",
        type=int,
        default=2048,
        help="Teacher HTML token cap (run scripts/stats_html_token_lengths.py). Mixing Design2Code GT often needs 8192+.",
    )
    p.add_argument("--batch_size", type=int, default=1)
    p.add_argument("--grad_accum", type=int, default=8)
    p.add_argument("--lr_compressor", type=float, default=2e-4)
    p.add_argument("--lr_lora", type=float, default=2e-5)
    p.add_argument("--target_tokens", type=int, default=256)
    p.add_argument("--lora_r", type=int, default=16)
    p.add_argument("--lora_alpha", type=int, default=32)
    p.add_argument(
        "--disable_lora",
        action="store_true",
        help="Disable LoRA adapters; train compressor-only for ablation.",
    )
    p.add_argument("--resume", type=str, default=None)
    p.add_argument(
        "--mix_root",
        default=None,
        help="If set (e.g. data), concat extra (image,html) pairs under mix_images_subdir + mix_gt_subdir.",
    )
    p.add_argument(
        "--mix_images_subdir",
        default="ref_screenshots_websight",
        help="Relative to mix_root; default matches data/ref_screenshots_websight + websight_gt_html.",
    )
    p.add_argument("--mix_gt_subdir", default="websight_gt_html")
    p.add_argument(
        "--mix_max_samples",
        type=int,
        default=None,
        help="Cap mixed split size (default: all pairs that have GT).",
    )
    p.add_argument(
        "--eval_after_epoch",
        action="store_true",
        help="After each epoch: save ckpt, free GPU, run eval_all (uipress) + CLIP (single-GPU only).",
    )
    p.add_argument("--eval_max_samples", type=int, default=50)
    p.add_argument(
        "--eval_output_dir",
        default=None,
        help="Defaults to results/clip_per_epoch/<output_dir name>.",
    )
    p.add_argument("--eval_data_dir", default="data")
    p.add_argument("--eval_ref_dir", default="data/ref_screenshots")
    p.add_argument(
        "--eval_clip_device",
        default="cuda",
        choices=["cuda", "cpu"],
        help="Device for CLIP ViT in post-epoch scoring.",
    )
    return p.parse_args()


if __name__ == "__main__":
    train(parse_args())