(encoder)
| 586 | |
| 587 | |
| 588 | def transformers_gemma3_from_encoder(encoder): |
| 589 | jsons_path = Path(__file__).parent / "gemma_configs" |
| 590 | config = Gemma3Config.from_json_file(jsons_path / "gemma3cfg.json") |
| 591 | with torch.device("meta"): |
| 592 | metamodel = Gemma3ForConditionalGeneration(config) |
| 593 | t_model_name = config.text_config.model_type |
| 594 | t_model = _locate_model_within_model(metamodel, t_model_name) |
| 595 | if t_model is None: |
| 596 | raise ValueError( |
| 597 | "Can't locate text model while converting text encoder to Gemma3ForConditionalGeneration" |
| 598 | ) |
| 599 | t_model.load_state_dict( |
| 600 | encoder.gemma3_12b.transformer.model.state_dict(), assign=True, strict=False |
| 601 | ) |
| 602 | v_tower_name = config.vision_config.model_type |
| 603 | v_tower = _locate_model_within_model(metamodel, v_tower_name) |
| 604 | if v_tower is None: |
| 605 | raise ValueError( |
| 606 | "Can't locate vision model while converting text encoder to Gemma3ForConditionalGeneration" |
| 607 | ) |
| 608 | v_model = v_tower.vision_model |
| 609 | v_model.load_state_dict( |
| 610 | encoder.gemma3_12b.transformer.vision_model.state_dict(), |
| 611 | assign=True, |
| 612 | strict=False, |
| 613 | ) |
| 614 | metamodel.multi_modal_projector.load_state_dict( |
| 615 | encoder.gemma3_12b.transformer.multi_modal_projector.state_dict(), |
| 616 | assign=True, |
| 617 | strict=False, |
| 618 | ) |
| 619 | config = config.text_config |
| 620 | dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) |
| 621 | base = config.rope_local_base_freq |
| 622 | |
| 623 | device = encoder.device |
| 624 | positions_length = len(v_model.embeddings.position_ids[0]) |
| 625 | position_ids = torch.arange( |
| 626 | positions_length, dtype=torch.long, device="cpu" |
| 627 | ).unsqueeze(0) |
| 628 | v_model.embeddings.register_buffer("position_ids", position_ids) |
| 629 | embed_scale = torch.tensor(config.hidden_size**0.5, device=device) |
| 630 | t_model.embed_tokens.register_buffer("embed_scale", embed_scale) |
| 631 | local_rope_freqs = 1.0 / ( |
| 632 | base |
| 633 | ** ( |
| 634 | torch.arange(0, dim, 2, dtype=torch.int64).to( |
| 635 | device=device, dtype=torch.float |
| 636 | ) |
| 637 | / dim |
| 638 | ) |
| 639 | ) |
| 640 | t_model.rotary_emb_local.register_buffer("inv_freq", local_rope_freqs) |
| 641 | rope_freqs, _ = ROPE_INIT_FUNCTIONS[config.rope_scaling["rope_type"]]( |
| 642 | config, device |
| 643 | ) |
| 644 | t_model.rotary_emb.register_buffer("inv_freq", rope_freqs) |
| 645 | lm_head_requires_grad = False |
no test coverage detected