"""MiniClef-4B: Qwen3.5-4B backbone + dynamic decision head.""" from __future__ import annotations import json import os from typing import Any, Dict, List, Optional import torch import torch.nn as nn import torch.nn.functional as F from .decision_head import DynamicDecisionHead from .losses import batch_loss from .preprocessing import build_option_text BACKBONE_ID = "Qwen/Qwen3.5-4B" class MiniClef4B(nn.Module): """Structured decision model. Pipeline: State + Schema -> Qwen3.5-4B backbone -> hidden -> question-conditioned (question text is part of input) -> DynamicDecisionHead -> per-question scoring -> softmax -> structured distributions. No fixed classifiers. Variable questions/choices. Text + optional images/videos (multimodal-ready; V0 uses text path but processor path is preserved). """ def __init__( self, backbone_id: str = BACKBONE_ID, hidden_size: int = 2560, head_intermediate: int = 1024, head_dropout: float = 0.1, max_length: int = 1024, freeze_backbone: bool = True, ): super().__init__() self.backbone_id = backbone_id self.hidden_size = hidden_size self.max_length = max_length self.processor = None self.tokenizer = None self.backbone = None # Qwen3_5Model self.head = DynamicDecisionHead( hidden_size=hidden_size, intermediate_size=head_intermediate, dropout=head_dropout, ) self._freeze_backbone_flag = freeze_backbone # ---------- construction ---------- @classmethod def load_backbone_and_processor( cls, backbone_id: str = BACKBONE_ID, dtype: torch.dtype = torch.bfloat16, attn_implementation: Optional[str] = None, gradient_checkpointing: bool = True, device_map: Optional[str] = None, ): """Load processor + Qwen3_5Model trunk. Verifies real HF API (no invented classes).""" from transformers import AutoProcessor, Qwen3_5Model, Qwen3_5Config processor = AutoProcessor.from_pretrained(backbone_id, trust_remote_code=True) # attention: auto-detect; sdpa on T4, flash on H100 if available model_kwargs: Dict[str, Any] = {"trust_remote_code": True} # transformers 5.x uses `dtype`; older uses `torch_dtype`. Pass both-safe via dtype. try: cfg = Qwen3_5Config.from_pretrained(backbone_id) hidden = cfg.text_config.hidden_size except Exception: hidden = 2560 if attn_implementation is not None: model_kwargs["attn_implementation"] = attn_implementation # dtype handling model_kwargs["dtype"] = dtype if device_map is not None: model_kwargs["device_map"] = device_map backbone = Qwen3_5Model.from_pretrained(backbone_id, **model_kwargs) if gradient_checkpointing and hasattr(backbone, "gradient_checkpointing_enable"): try: backbone.gradient_checkpointing_enable() except Exception: pass return processor, backbone, hidden @classmethod def create( cls, backbone_id: str = BACKBONE_ID, dtype: torch.dtype = torch.bfloat16, attn_implementation: Optional[str] = None, freeze_backbone: bool = True, gradient_checkpointing: bool = True, device_map: Optional[str] = None, max_length: int = 1024, head_intermediate: int = 1024, head_dropout: float = 0.1, ) -> "MiniClef4B": from transformers import Qwen3_5Config try: cfg = Qwen3_5Config.from_pretrained(backbone_id) hidden = cfg.text_config.hidden_size except Exception: hidden = 2560 obj = cls( backbone_id=backbone_id, hidden_size=hidden, head_intermediate=head_intermediate, head_dropout=head_dropout, max_length=max_length, freeze_backbone=freeze_backbone, ) processor, backbone, _ = cls.load_backbone_and_processor( backbone_id=backbone_id, dtype=dtype, attn_implementation=attn_implementation, gradient_checkpointing=gradient_checkpointing, device_map=device_map, ) obj.processor = processor # processor may be Qwen3VLProcessor with .tokenizer obj.tokenizer = processor.tokenizer if hasattr(processor, "tokenizer") else processor obj.backbone = backbone if freeze_backbone: obj.freeze_backbone() else: obj.unfreeze_backbone() return obj # ---------- backbone control ---------- def freeze_backbone(self): if self.backbone is not None: for p in self.backbone.parameters(): p.requires_grad = False self._freeze_backbone_flag = True def unfreeze_backbone(self): if self.backbone is not None: for p in self.backbone.parameters(): p.requires_grad = True self._freeze_backbone_flag = False def unfreeze_top_layers(self, n_layers: int): """Progressively unfreeze upper layers for Phase 3 experiments.""" if self.backbone is None: raise ValueError("backbone not loaded") # Qwen3_5Model: backbone.language_model.layers or .layers? inspect dynamically layers = None for attr in ("layers", "language_model", "model", "text_model"): if hasattr(self.backbone, attr): cand = getattr(self.backbone, attr) if hasattr(cand, "layers"): layers = cand.layers break if hasattr(cand, "language_model") and hasattr(cand.language_model, "layers"): layers = cand.language_model.layers break # fallback: search named_parameters for 'layers.' if layers is None: # freeze all then unfreeze by name pattern for last n_layers for p in self.backbone.parameters(): p.requires_grad = False # collect layer indices import re idxs = set() for n, _ in self.backbone.named_parameters(): m = re.search(r"layers\.(\d+)\.", n) if m: idxs.add(int(m.group(1))) if len(idxs) == 0: raise ValueError("cannot locate transformer layers for partial unfreeze") top = sorted(idxs)[-n_layers:] for n, p in self.backbone.named_parameters(): m = re.search(r"layers\.(\d+)\.", n) if m and int(m.group(1)) in top: p.requires_grad = True return # freeze all, unfreeze top n for p in self.backbone.parameters(): p.requires_grad = False for layer in layers[-n_layers:]: for p in layer.parameters(): p.requires_grad = True def apply_lora(self, r: int = 16, alpha: int = 32, dropout: float = 0.05, target_modules: Optional[List[str]] = None): """Attach LoRA/PEFT to Qwen3.5-4B backbone (Phase 3).""" try: from peft import LoraConfig, get_peft_model, TaskType except ImportError as e: raise ImportError("peft is required for LoRA; pip install peft") from e if self.backbone is None: raise ValueError("backbone not loaded") if target_modules is None: target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"] # Backbone is Qwen3_5Model (feature trunk, not a CausalLM wrapper), so use # FEATURE_EXTRACTION to avoid prepare_inputs_for_generation requirement. cfg = LoraConfig(r=r, lora_alpha=alpha, lora_dropout=dropout, target_modules=target_modules, bias="none", task_type=TaskType.FEATURE_EXTRACTION) self.backbone = get_peft_model(self.backbone, cfg) # ---------- tokenization / forward ---------- def _build_texts(self, batch: Dict[str, Any]) -> tuple[List[str], List[int]]: texts: List[str] = [] sizes: List[int] = [] for st, q, opts, kind in zip(batch["state_texts"], batch["questions"], batch["options_list"], batch["kinds"]): if len(opts) == 0: raise ValueError("question choices are empty") sizes.append(len(opts)) for o in opts: texts.append(build_option_text(st, q, o, kind)) return texts, sizes def _tokenize(self, texts: List[str], device: torch.device) -> Dict[str, torch.Tensor]: if self.tokenizer is None: raise ValueError("tokenizer not loaded") enc = self.tokenizer( texts, padding=True, truncation=True, max_length=self.max_length, return_tensors="pt", ) return {k: v.to(device) for k, v in enc.items()} def forward( self, batch: Dict[str, Any], targets: Optional[torch.Tensor] = None, loss_mode: str = "mean", forward_chunk_size: int = 8, ) -> Dict[str, Any]: """Forward over a collated flat batch (variable K). Args: batch: output of collate_flat_texts. targets: optional [sum(K)] float tensor for loss. If None, built from batch. loss_mode: 'mean' or 'sum'. forward_chunk_size: max #option-sequences per backbone forward (memory saver for large K on T4/H100; gradients still flow across chunks). Returns: dict with flat_logits [N], per-question logits/probs lists, sizes, loss (if targets). """ if self.backbone is None: raise ValueError("backbone not loaded; call MiniClef4B.create() first") device = next(self.backbone.parameters()).device # Handle LiteBackbone (testing without HF weights): it exposes .device or parameters texts, sizes = self._build_texts(batch) tok = self._tokenize(texts, device) # Multimodal extension point: if images/videos present, route via processor. # V0 text-only: backbone text path with input_ids/attention_mask. # If future states include PIL images, processor __call__ handles them; # here we keep the simple reliable path but preserve the hook: has_media = any(len(x) > 0 for x in batch.get("state_images", [])) or any( len(x) > 0 for x in batch.get("state_videos", []) ) if has_media: # Full processor path (images/videos aligned per-option is non-trivial; # for now broadcast first image per question; explicit error if malformed). raise ValueError( "multimodal inputs detected but per-option media batching is not yet wired for training; " "use text-only V0 path or extend _tokenize_with_media()" ) out_chunks: List[torch.Tensor] = [] input_ids = tok["input_ids"] attn = tok.get("attention_mask", None) n = input_ids.shape[0] for s in range(0, n, forward_chunk_size): e = min(s + forward_chunk_size, n) chunk_kwargs: Dict[str, Any] = {"input_ids": input_ids[s:e]} if attn is not None: chunk_kwargs["attention_mask"] = attn[s:e] out_c = self.backbone( **chunk_kwargs, use_cache=False, output_hidden_states=False, return_dict=True, ) hidden_c = out_c.last_hidden_state # [c, L, H] logits_c = self.head(hidden_c, chunk_kwargs.get("attention_mask", None)) out_chunks.append(logits_c) flat_logits = torch.cat(out_chunks, dim=0) # [N] # Split per question per_q_logits: List[torch.Tensor] = [] per_q_probs: List[torch.Tensor] = [] off = 0 for k in sizes: lg = flat_logits[off : off + k] per_q_logits.append(lg) per_q_probs.append(F.softmax(lg.float(), dim=-1)) off += k result: Dict[str, Any] = { "flat_logits": flat_logits, "per_question_logits": per_q_logits, "per_question_probs": per_q_probs, "sizes": sizes, "kinds": batch["kinds"], } if targets is None: # build from batch targets_list import torch as _t flat_t = [] for t in batch["targets_list"]: flat_t.extend([float(v) for v in t]) targets = _t.tensor(flat_t, dtype=_t.float32, device=flat_logits.device) loss, per_q_loss = batch_loss(flat_logits, targets.to(flat_logits.device), sizes, kinds=batch["kinds"], mode=loss_mode) result["loss"] = loss result["per_question_loss"] = per_q_loss return result @torch.no_grad() def predict_structured(self, state: Dict[str, Any], schema: Dict[str, Any]) -> Dict[str, Dict[str, float]]: """Produce structured distributions for dynamic schema (eval/demo). Args: state: {"text": str, ...} schema: {"questions": [{"id":..., "type":..., "question":..., "choices":[...], "kind"?}]} """ if "text" not in state: raise ValueError("dataset field missing: state['text']") questions = schema.get("questions", None) if questions is None or len(questions) == 0: raise ValueError("question choices are empty: schema has no questions") batch = { "state_texts": [], "questions": [], "options_list": [], "kinds": [], "targets_list": [], "state_images": [], "state_videos": [], } # Map generic type -> kind for loss/dispatch (categorical->choice etc.) type_to_kind = {"categorical": "choice", "boolean": "noul", "ordinal": "score", "choice": "choice", "noul": "noul", "score": "score"} for q in questions: if "choices" not in q or not q["choices"]: raise ValueError(f"question choices are empty: id={q.get('id')}") kind = q.get("kind", None) or type_to_kind.get(q.get("type", "categorical"), "choice") if kind not in ("choice", "noul", "score"): raise ValueError(f"unsupported decision type: kind='{kind}' id={q.get('id')}") batch["state_texts"].append(state["text"]) batch["questions"].append(q.get("question", q["id"])) batch["options_list"].append(list(q["choices"])) batch["kinds"].append(kind) batch["targets_list"].append([1.0 / len(q["choices"])] * len(q["choices"])) batch["state_images"].append(state.get("images", [])) batch["state_videos"].append(state.get("videos", [])) was_training = self.training self.eval() out = self.forward(batch, targets=None) if was_training: self.train() structured: Dict[str, Dict[str, float]] = {} for q, probs in zip(questions, out["per_question_probs"]): d = {c: float(p) for c, p in zip(q["choices"], probs.detach().cpu().tolist())} # normalize defensively s = sum(d.values()) if s > 0: d = {k: v / s for k, v in d.items()} structured[q["id"]] = d return structured # ---------- persistence (HF-compatible) ---------- def save_pretrained(self, save_dir: str): os.makedirs(save_dir, exist_ok=True) # head torch.save(self.head.state_dict(), os.path.join(save_dir, "decision_head.pt")) # model config cfg = { "backbone_id": self.backbone_id, "hidden_size": self.hidden_size, "max_length": self.max_length, "architectures": ["MiniClef4B"], "model_type": "miniclef-4b", } with open(os.path.join(save_dir, "miniclef_config.json"), "w") as f: json.dump(cfg, f, indent=2) # backbone + processor via HF (only if not LoRA-merged? save as usual) try: if self.backbone is not None and hasattr(self.backbone, "save_pretrained"): # avoid duplicating 8GB in small checkpoints? Still save for HF-compat. # To keep V0 checkpoints light, save backbone only on demand via save_backbone flag. pass except Exception: pass if self.processor is not None and hasattr(self.processor, "save_pretrained"): try: self.processor.save_pretrained(save_dir) except Exception: pass if self.tokenizer is not None and hasattr(self.tokenizer, "save_pretrained"): try: self.tokenizer.save_pretrained(save_dir) except Exception: pass def save_head_only(self, path: str): torch.save({"head": self.head.state_dict(), "config": {"hidden_size": self.hidden_size, "backbone_id": self.backbone_id}}, path) def load_head_only(self, path: str, map_location=None): ckpt = torch.load(path, map_location=map_location or "cpu") state = ckpt["head"] if "head" in ckpt else ckpt self.head.load_state_dict(state) return self