import torchfrom transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B", torch_dtype=torch.bfloat16) # หา text-decoder layer list (เลี่ยง vision encoder กรณี multimodal)holder, layers = None, Nonefor _, mod in model.named_modules(): L = getattr(mod, "layers", None) if isinstance(L, torch.nn.ModuleList) and len(L) and hasattr(L[0], "self_attn"): holder, layers = mod, L if "language" in _.lower() or "text" in _.lower(): breakN = len(layers) # เก็บ 18 จาก 36 layers: หัว + ท้ายkeep = [0,1,2,3,4,5,6,7,8, 27,28,29,30,31,32,33,34,35]holder.layers = torch.nn.ModuleList([layers[i] for i in keep]) # อัปเดต config (รองรับ nested text_config ของ Gemma3)for c in {model.config, getattr(model.config, "text_config", model.config)}: if getattr(c, "num_hidden_layers", None) is not None: c.num_hidden_layers = len(keep) lt = getattr(c, "layer_types", None) if isinstance(lt, list) and len(lt) == N: c.layer_types = [lt[i] for i in keep] # reindex layer_idx ของแต่ละ block (สำคัญต่อ KV cache)for i, lyr in enumerate(holder.layers): if hasattr(lyr, "self_attn") and hasattr(lyr.self_attn, "layer_idx"): lyr.self_attn.layer_idx = i