
scripts/preprocess/get_dmole_arch.py:7-85
7: def get_enable_layers(scores: pd.DataFrame, budget_portion: float):
8:     # Split scores into LLM and ViT scores
9:     llm_scores = (
10:         scores[scores["layer"].str.contains("language_model")]
11:         .sort_values(by="score", ascending=False)
12:         .reset_index(drop=True)
13:     )
14:     vit_scores = (
15:         scores[scores["layer"].str.contains("vision_model")]
16:         .sort_values(by="score", ascending=False)
17:         .reset_index(drop=True)
18:     )
19: 
20:     # Calculate adaptive budget portions for LLM and ViT
21:     total_score = llm_scores["score"].sum() + vit_scores["score"].sum()
22:     llm_budget_portion = llm_scores["score"].sum() / total_score
23:     vit_budget_portion = vit_scores["score"].sum() / total_score
24: 
25:     # Calculate the number of layers to enable based on budget portion for LLM and ViT
26:     total_budget = int(len(scores) * budget_portion + 0.5)
27: 
28:     # Set minimum portion for ViT layers to at least 1/4 of the total budget
29:     vit_min_budget = max(
30:         int(total_budget * 0.25), int(total_budget * vit_budget_portion + 0.5)
31:     )
32:     llm_enable_layers_count = total_budget - vit_min_budget
33: 
34:     # Select top layers from LLM and ViT
35:     enable_layers = []
36: 
37:     # LLM layers selection
38:     if llm_enable_layers_count > 0:
39:         llm_threshold = llm_scores.iloc[llm_enable_layers_count - 1]["score"]
40:         llm_enable_layers = list(
41:             llm_scores[llm_scores["score"] > llm_threshold]["layer"]
42:         )
43: 
44:         if len(llm_scores[llm_scores["score"] == llm_threshold]) > 1:
45:             remaining_layers = llm_scores[llm_scores["score"] == llm_threshold][
46:                 "layer"
47:             ].sample(
48:                 n=llm_enable_layers_count - len(llm_enable_layers), random_state=42
49:             )
50:             llm_enable_layers.extend(remaining_layers.tolist())
51:         else:
52:             llm_enable_layers = list(
53:                 llm_scores[llm_scores["score"] >= llm_threshold]["layer"]
54:             )
55: 
56:     # ViT layers selection
57:     if vit_min_budget > 0:
58:         vit_threshold = vit_scores.iloc[vit_min_budget - 1]["score"]
59:         vit_enable_layers = list(
60:             vit_scores[vit_scores["score"] > vit_threshold]["layer"]
61:         )
62: 
63:         if len(vit_scores[vit_scores["score"] == vit_threshold]) > 1:
64:             remaining_layers = vit_scores[vit_scores["score"] == vit_threshold][
65:                 "layer"
66:             ].sample(n=vit_min_budget - len(vit_enable_layers), random_state=42)
67:             vit_enable_layers.extend(remaining_layers.tolist())
68:         else:
69:             vit_enable_layers = list(
70:                 vit_scores[vit_scores["score"] >= vit_threshold]["layer"]
71:             )
72: 
73:     # Combine LLM and ViT enabled layers
74:     enable_layers.extend(llm_enable_layers)
75:     enable_layers.extend(vit_enable_layers)
76: 
77:     # Format layer names if "base_model" exists in the names
78:     if enable_layers and "base_model" in enable_layers[0]:
79:         enable_layers = [".".join(layer.split(".")[2:]) for layer in enable_layers]
80:     else:
81:         enable_layers = [".".join(layer.split(".")[0:]) for layer in enable_layers]
82: 
83:     # Ensure that the number of enabled layers matches the expected count
84:     assert (
85:         len(enable_layers) == total_budget

scripts/preprocess/get_dmole_arch.py:118-130
118:             cur_arch[layer] = []
119: 
120:     enable_layers = get_enable_layers(dataframes[taskname], budget_portion=0.5)
121:     for layer in enable_layers:
122:         if layer not in cur_arch:
123:             cur_arch[layer] = [i]
124:         else:
125:             cur_arch[layer].append(i)
126: 
127:     # save the current architecture and sort keys
128:     os.makedirs("dmole_arch", exist_ok=True)
129:     with open(f"dmole_arch/{i}_InternVL2-2B_{taskname}_arch.json", "w") as f:
130:         json.dump(cur_arch, f, indent=4, sort_keys=True)

internvl/scorer/compute_zc_score.py:386-433
386:     portion = model_args.zc_proxy_score_portion
387:     max_batch_num = int(len(train_dataloader) * portion + 0.5)
388: 
389:     logger.info(
390:         f"Zero-cost proxy score portion: {portion}, max_batch_num: {max_batch_num}"
391:     )
392: 
393:     model = trainer._wrap_model(model).to(trainer.args.device)
394: 
395:     model.train()
396:     model.zero_grad()
397:     for i, inputs in tqdm(enumerate(train_dataloader), total=max_batch_num):
398:         if i > max_batch_num:
399:             break
400: 
401:         inputs = trainer._prepare_inputs(inputs)
402:         loss = trainer.compute_loss(model, inputs)
403: 
404:         loss.backward()
405: 
406:     logger.info("Finished computing zero-shot proxy score.")
407: 
408:     logger.info("Computing zero-shot proxy score for each layer...")
409: 
410:     target_modules = ["attention.wqkv", "attention.wo", "attn.qkv", "attn.proj"]
411: 
412:     if torch.distributed.get_rank() == 0:
413:         zc_proxy_score = defaultdict(float)
414: 
415:         for name, module in model.named_modules():
416:             if any([name.endswith(target) for target in target_modules]):
417:                 for param in module.parameters():
418:                     if param.grad is not None:
419:                         zc_proxy_score[name] += param.grad.norm().item()
420:                 zc_proxy_score[name] *= torch.cuda.device_count()
421: 
422:         # sorting by score
423:         zc_proxy_score = sorted(
424:             zc_proxy_score.items(), key=lambda x: x[1], reverse=True
425:         )
426: 
427:         # save to csv
428:         os.makedirs(os.path.dirname(model_args.zc_proxy_score_save_path), exist_ok=True)
429: 
430:         # note that zc_proxy_score is already a list, so we can directly use it
431:         df = DataFrame(zc_proxy_score, columns=["layer", "score"])
432: 
433:         df.to_csv(model_args.zc_proxy_score_save_path, index=False)

internvl/model/internvl_chat/modeling_internvl_chat.py:131-169
131:         self.autoencoders = nn.ModuleList()
132:         self.thresholds = []
133: 
134:         dmole_arch = llm_dmole_arch = vision_dmole_arch = None
135:         if config.use_dmole:
136:             with open(config.dmole_arch_path, "r") as f:
137:                 dmole_arch = json.load(f)
138:             vision_dmole_arch = {
139:                 ".".join(k.split(".")[1:]): v
140:                 for k, v in dmole_arch.items()
141:                 if "vision" in k
142:             }
143:             llm_dmole_arch = {
144:                 ".".join(k.split(".")[1:]): v
145:                 for k, v in dmole_arch.items()
146:                 if "language_model" in k
147:             }
148:             rank0_print("dmole_arch:", dmole_arch, "path:", config.dmole_arch_path)
149:             rank0_print("vision_dmole_arch:", vision_dmole_arch)
150:             rank0_print("llm_dmole_arch:", llm_dmole_arch)
151:             if config.autoencoder_path is None:
152:                 config.autoencoder_path = "autoencoder_models"
153:             self.load_autoencoder(config.autoencoder_path)
154:             rank0_print("suceesfully loaded autoencoder from ", config.autoencoder_path)
155: 
156:         if config.use_backbone_lora:
157:             self.wrap_backbone_lora(
158:                 r=config.use_backbone_lora,
159:                 lora_alpha=2 * config.use_backbone_lora,
160:                 dmole_arch=vision_dmole_arch,
161:             )
162: 
163:         if config.use_llm_lora:
164:             self.wrap_llm_lora(
165:                 r=config.use_llm_lora,
166:                 lora_alpha=2 * config.use_llm_lora,
167:                 dmole_arch=llm_dmole_arch,
168:             )
169: 

internvl/model/internvl_chat/modeling_internvl_chat.py:170-250
170:     def wrap_backbone_lora(
171:         self,
172:         r=128,
173:         lora_alpha=256,
174:         lora_dropout=0.05,
175:         adapter_name="default",
176:         dmole_arch=None,
177:     ):
178:         lora_config = MoELoraConfig(
179:             r=r,
180:             target_modules=["attn.qkv", "attn.proj", "mlp.fc1", "mlp.fc2"],
181:             lora_alpha=lora_alpha,
182:             lora_dropout=lora_dropout,
183:             dmole_arch=dmole_arch,
184:         )
185: 
186:         if dmole_arch is not None:
187:             lora_config._register_custom_module({nn.Linear: DMoLELinear})
188: 
189:         with hijack_peft_mappings():
190:             self.vision_model = get_peft_model(
191:                 self.vision_model, lora_config, adapter_name=adapter_name
192:             )
193: 
194:         self.vision_model.enable_input_require_grads()
195:         rank0_print(f"Wrapping backbone lora: ", end="")
196:         self.vision_model.print_trainable_parameters()
197: 
198:     def wrap_llm_lora(
199:         self,
200:         r=128,
201:         lora_alpha=256,
202:         lora_dropout=0.05,
203:         adapter_name="default",
204:         dmole_arch=None,
205:     ):
206:         # Determine the target modules based on the architecture of the language model
207:         if self.llm_arch_name == "InternLM2ForCausalLM":
208:             target_modules = [
209:                 "attention.wqkv",
210:                 "attention.wo",
211:                 "feed_forward.w1",
212:                 "feed_forward.w2",
213:                 "feed_forward.w3",
214:             ]
215:         elif self.llm_arch_name == "Phi3ForCausalLM":
216:             target_modules = [
217:                 "mlp.down_proj",
218:                 "mlp.gate_up_proj",
219:                 "self_attn.o_proj",
220:                 "self_attn.qkv_proj",
221:             ]
222:         elif self.llm_arch_name in ["Qwen2ForCausalLM", "LlamaForCausalLM"]:
223:             target_modules = [
224:                 "self_attn.q_proj",
225:                 "self_attn.k_proj",
226:                 "self_attn.v_proj",
227:                 "self_attn.o_proj",
228:                 "mlp.gate_proj",
229:                 "mlp.down_proj",
230:                 "mlp.up_proj",
231:             ]
232:         else:
233:             raise NotImplemented
234: 
235:         lora_config = MoELoraConfig(
236:             r=r,
237:             target_modules=target_modules,
238:             lora_alpha=lora_alpha,
239:             lora_dropout=lora_dropout,
240:             task_type="CAUSAL_LM",
241:             dmole_arch=dmole_arch,
242:         )
243:         if dmole_arch is not None:
244:             lora_config._register_custom_module({nn.Linear: DMoLELinear})
245: 
246:         with hijack_peft_mappings():
247:             self.language_model = get_peft_model(
248:                 self.language_model, lora_config, adapter_name=adapter_name
249:             )
250:         self.language_model.enable_input_require_grads()

internvl/model/internvl_chat/modeling_internvl_chat.py:383-436
383:     def extract_sequence_feature(
384:         self,
385:         pixel_values: torch.FloatTensor,
386:         input_ids: torch.LongTensor = None,
387:         attention_mask: Optional[torch.Tensor] = None,
388:         position_ids: Optional[torch.LongTensor] = None,
389:         image_flags: Optional[torch.LongTensor] = None,
390:         past_key_values: Optional[List[torch.FloatTensor]] = None,
391:         labels: Optional[torch.LongTensor] = None,
392:         use_cache: Optional[bool] = None,
393:         output_attentions: Optional[bool] = None,
394:         output_hidden_states: Optional[bool] = None,
395:         return_dict: Optional[bool] = None,
396:     ):
397: 
398:         vit_embeds = self.vision_model(
399:             pixel_values=pixel_values,
400:             output_hidden_states=False,
401:             return_dict=True,
402:         ).last_hidden_state
403:         vit_embeds_max = vit_embeds.max(dim=1).values
404: 
405:         inputs_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
406: 
407:         if not isinstance(self.language_model, PeftModel):
408:             outputs = self.language_model.model(
409:                 attention_mask=attention_mask,
410:                 position_ids=position_ids,
411:                 past_key_values=past_key_values,
412:                 inputs_embeds=inputs_embeds,
413:                 use_cache=use_cache,
414:                 output_attentions=output_attentions,
415:                 output_hidden_states=output_hidden_states,
416:                 return_dict=True,
417:             )
418:             llm_embeds = outputs.last_hidden_state
419:         else:
420:             outputs = self.language_model.model.base_model(
421:                 inputs_embeds=inputs_embeds,
422:                 attention_mask=attention_mask,
423:                 position_ids=position_ids,
424:                 past_key_values=past_key_values,
425:                 use_cache=use_cache,
426:                 output_attentions=output_attentions,
427:                 output_hidden_states=output_hidden_states,
428:                 return_dict=True,
429:             )
430:             llm_embeds = outputs.last_hidden_state
431: 
432:         llm_embeds_max = llm_embeds.max(dim=1).values
433: 
434:         return torch.cat([vit_embeds_max, llm_embeds_max], dim=1)
435: 
436:     @torch.no_grad()

internvl/model/internvl_chat/modeling_internvl_chat.py:551-619
551:     def load_autoencoder(self, base_autoencoder_path):
552:         TASKS = [
553:             "vizwiz_caption",
554:             "skvg",
555:             "textcaps",
556:             "iconqa",
557:             "ocrvqa",
558:             "flickr30k",
559:             "vizwiz",
560:             "kvqa",
561:             "pmcvqa",
562:         ]
563: 
564:         # Iterate through the tasks and load corresponding autoencoder and threshold
565:         for task in TASKS[: self.config.task_id]:
566:             autoencoder_file = os.path.join(
567:                 base_autoencoder_path, task, "autoencoder.pt"
568:             )
569:             threshold_file = os.path.join(base_autoencoder_path, task, "threshold.txt")
570: 
571:             rank0_print(
572:                 f"Loading autoencoder and threshold for task {task} from {autoencoder_file} and {threshold_file}"
573:             )
574: 
575:             try:
576:                 # Load the state dict to infer dimensions
577:                 state_dict = torch.load(autoencoder_file, map_location=self.device)
578: 
579:                 # Auto-set input_dim and hidden_dim based on state_dict
580:                 # Example: assuming 'encoder_layer.weight' holds the relevant dimension
581:                 for key, value in state_dict.items():
582:                     if (
583:                         "weight" in key
584:                     ):  # Find a key with 'weight', usually containing the layer shape
585:                         input_dim = value.size(1)  # Number of input features
586:                         hidden_dim = value.size(
587:                             0
588:                         )  # Number of output features (hidden layer size)
589:                         break  # Found the dimensions, break the loop
590: 
591:                 rank0_print(
592:                     f"Inferred dimensions for autoencoder - input_dim: {input_dim}, hidden_dim: {hidden_dim}"
593:                 )
594: 
595:                 # Create and load the autoencoder with inferred dimensions
596:                 autoencoder = AutoEncoder(input_dim=input_dim, hidden_dim=hidden_dim)
597:                 autoencoder.load_state_dict(state_dict)
598: 
599:                 self.autoencoders.append(autoencoder)
600: 
601:                 # Load threshold
602:                 with open(threshold_file, "r") as f:
603:                     threshold = float(f.read().strip())
604:                 self.thresholds.append(threshold)
605: 
606:             except FileNotFoundError as e:
607:                 rank0_print(
608:                     f"File not found: {e.filename}, please check the file path."
609:                 )
610:                 exit(0)
611:             except Exception as e:
612:                 rank0_print(
613:                     f"Error occurred while loading autoencoder or threshold for task {task}: {str(e)}"
614:                 )
615:                 exit(0)
616: 
617:         self.autoencoders = self.autoencoders.to(self.device)
618:         self.autoencoders.requires_grad_(False)
619:         rank0_print("Autoencoders and thresholds have been loaded.")

internvl/model/internvl_chat/modeling_internvl_chat.py:661-704
661: 
662:     def process_inputs(
663:         self,
664:         tokenizer,
665:         input_ids,
666:         pixel_values,
667:         num_patches_list,
668:         IMG_START_TOKEN="<img>",
669:         IMG_END_TOKEN="</img>",
670:         IMG_CONTEXT_TOKEN="<IMG_CONTEXT>",
671:     ):
672:         # last pixel value of each patch is the thumbnail, extract it with num_patches_list
673:         thumb_pixel_values = []
674:         idx_shift = 0
675:         for num_patches in num_patches_list:
676:             thumb_pixel_values.append(pixel_values[idx_shift + num_patches - 1])
677:             idx_shift += num_patches
678:         thumb_pixel_values = torch.stack(thumb_pixel_values)
679: 
680:         img_tokens = [IMG_START_TOKEN, IMG_END_TOKEN, IMG_CONTEXT_TOKEN]
681:         img_token_ids = tokenizer.convert_tokens_to_ids(img_tokens)
682:         img_token_ids = torch.tensor(img_token_ids, device=input_ids.device)
683: 
684:         sep_token_id = tokenizer.convert_tokens_to_ids("<|im_end|>")
685: 
686:         text_input_ids = []
687:         for i in range(input_ids.size(0)):
688:             cur_input_ids = input_ids[i]
689:             sep_positions = (cur_input_ids == sep_token_id).nonzero(as_tuple=True)[0]
690:             start_idx = sep_positions[0] + 1
691:             end_idx = sep_positions[1] + 1
692: 
693:             truncated_input_ids = cur_input_ids[start_idx:end_idx]
694: 
695:             mask = ~torch.isin(truncated_input_ids, img_token_ids)
696:             truncated_input_ids = truncated_input_ids[mask]
697:             text_input_ids.append(truncated_input_ids)
698:         pad_sequence = torch.nn.utils.rnn.pad_sequence
699:         text_input_ids = pad_sequence(text_input_ids, batch_first=True, padding_value=0)
700:         text_attention_mask = text_input_ids != 0
701: 
702:         return thumb_pixel_values, text_input_ids, text_attention_mask
703: 
704:     def batch_chat(

internvl/model/internvl_chat/modeling_internvl_chat.py:736-783
736:         queries = []
737:         for idx, num_patches in enumerate(num_patches_list):
738:             question = questions[idx]
739:             if pixel_values is not None and "<image>" not in question:
740:                 question = "<image>\n" + question
741:             template = get_conv_template(self.template)
742:             template.system_message = self.system_message
743:             template.append_message(template.roles[0], question)
744:             template.append_message(template.roles[1], None)
745:             query = template.get_prompt()
746: 
747:             image_tokens = (
748:                 IMG_START_TOKEN
749:                 + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches
750:                 + IMG_END_TOKEN
751:             )
752:             query = query.replace("<image>", image_tokens, 1)
753:             queries.append(query)
754: 
755:         tokenizer.padding_side = "left"
756:         model_inputs = tokenizer(queries, return_tensors="pt", padding=True)
757:         device = torch.device(
758:             self.language_model.device if torch.cuda.is_available() else "cpu"
759:         )
760:         input_ids = model_inputs["input_ids"].to(device)
761:         attention_mask = model_inputs["attention_mask"].to(device)
762:         eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
763:         generation_config["eos_token_id"] = eos_token_id
764: 
765:         if self.config.use_dmole:
766:             self.set_expert_masks([])
767: 
768:             thumb_pixel_values, text_input_ids, text_attention_mask = (
769:                 self.process_inputs(
770:                     tokenizer, input_ids, pixel_values, num_patches_list
771:                 )
772:             )
773: 
774:             seq_rep = self.extract_sequence_feature(
775:                 pixel_values=thumb_pixel_values,
776:                 input_ids=text_input_ids,
777:                 attention_mask=text_attention_mask,
778:             )
779:             best_task_ids = self.get_task_ids(seq_rep)
780:             self.set_expert_masks(best_task_ids)
781: 
782:         generation_output = self.generate(
783:             pixel_values=pixel_values,

internvl/model/internvl_chat/modeling_internvl_chat.py:893-980
893:     def get_task_ids(
894:         self,
895:         seq_reps,
896:         mode="evaluation",
897:         current_task_id=None,
898:         second_task_threshold=0.3,
899:     ):
900:         batch_size = seq_reps.size(0)
901: 
902:         if len(self.autoencoders) == 0:
903:             return [] if mode == "evaluation" else [current_task_id]
904: 
905:         if mode == "training":
906:             if current_task_id is None:
907:                 raise ValueError("current_task_id is required for training mode")
908:             if current_task_id <= 1:
909:                 return [current_task_id]
910:             # Only consider autoencoders before current task
911:             available_autoencoders = min(current_task_id - 1, len(self.autoencoders))
912:             thresholds = np.array(self.thresholds[:available_autoencoders])
913:         else:  # evaluation mode
914:             available_autoencoders = len(self.autoencoders)
915:             thresholds = np.array(self.thresholds)
916: 
917:         if available_autoencoders == 0:
918:             return [] if mode == "evaluation" else [current_task_id]
919: 
920:         seq_reps = F.normalize(seq_reps, p=2, dim=1)
921:         mse_scores = np.zeros((batch_size, available_autoencoders))
922:         mse_loss = nn.MSELoss(reduction="none")
923: 
924:         # Calculate MSE scores
925:         for idx in range(available_autoencoders):
926:             autoencoder = self.autoencoders[idx].to(seq_reps.device)
927:             reconstructions = autoencoder(seq_reps).bfloat16()
928:             per_element_loss = mse_loss(reconstructions, seq_reps)
929:             per_sample_mse = per_element_loss.mean(dim=1)
930:             mse_scores[:, idx] = per_sample_mse.detach().cpu().float().numpy()
931: 
932:         # Find candidate tasks for each sample
933:         task_ids = np.full(batch_size, -1)
934: 
935:         for i in range(batch_size):
936:             below_threshold_indices = np.where(mse_scores[i, :] < thresholds)[0]
937: 
938:             if len(below_threshold_indices) > 0:
939:                 min_mse_idx = below_threshold_indices[
940:                     np.argmin(mse_scores[i, below_threshold_indices])
941:                 ]
942:                 task_ids[i] = min_mse_idx + 1  # 1-based indexing
943: 
944:         # Voting and selection logic
945:         valid_task_ids = task_ids[task_ids != -1]
946: 
947:         if len(valid_task_ids) == 0:
948:             return [] if mode == "evaluation" else [current_task_id]
949: 
950:         vote_counts = np.bincount(valid_task_ids)
951:         primary_task_id = np.argmax(vote_counts)
952:         primary_votes = vote_counts[primary_task_id]
953: 
954:         if mode == "training":
955:             # Training mode: always include current task + optionally one historical task
956:             result_tasks = [current_task_id]
957: 
958:             if primary_task_id != current_task_id:
959:                 historical_task_id = primary_task_id
960:                 support_rate = primary_votes / len(valid_task_ids)
961: 
962:                 if support_rate >= second_task_threshold:
963:                     result_tasks.append(historical_task_id)
964:         else:
965:             # Evaluation mode: original logic for 0-2 tasks
966:             result_tasks = [primary_task_id]
967: 
968:             if available_autoencoders > 1 and len(np.unique(valid_task_ids)) > 1:
969:                 remaining_votes = vote_counts.copy()
970:                 remaining_votes[primary_task_id] = 0
971: 
972:                 if np.max(remaining_votes) > 0:
973:                     secondary_task_id = np.argmax(remaining_votes)
974:                     secondary_votes = remaining_votes[secondary_task_id]
975:                     secondary_support_rate = secondary_votes / len(valid_task_ids)
976: 
977:                     if secondary_support_rate >= second_task_threshold:
978:                         result_tasks.append(secondary_task_id)
979: 
980:         return result_tasks

internvl/model/internvl_chat/modeling_internvl_chat.py:1024-1028
1024:     def set_expert_masks(self, task_id):
1025:         if self.config.use_backbone_lora:
1026:             self.vision_model.set_expert_masks(task_id)
1027:         if self.config.use_llm_lora:
1028:             self.language_model.set_expert_masks(task_id)

internvl/dmole/model.py:26-51
26:         if lora_config.dmole_arch and not any(
27:             prefix in current_key for prefix in lora_config.dmole_arch
28:         ):
29:             rank0_print(
30:                 f"Skipping {current_key} for D-MoLE because it is not in dmole_arch"
31:             )
32:             return
33: 
34:         if lora_config.dmole_arch and len(lora_config.dmole_arch[current_key]) == 0:
35:             rank0_print(
36:                 f"Skipping {current_key} for D-MoLE because it is empty in dmole_arch"
37:             )
38:             return
39: 
40:         if current_key is None:
41:             raise ValueError(
42:                 "Current Key shouldn't be `None` because it is the key of the target module"
43:             )
44: 
45:         rank0_print(f"Updating {current_key} for D-MoLE")
46: 
47:         expert_ids = num_experts = None
48:         if lora_config.dmole_arch:
49:             expert_ids = lora_config.dmole_arch.get(current_key)
50:             num_experts = len(expert_ids)
51: 

internvl/dmole/model.py:108-129
108:     def set_expert_masks(self, task_ids):
109:         if not isinstance(task_ids, list):
110:             task_ids = [task_ids]
111:         for _, layer in self.named_modules():
112:             if isinstance(layer, DMoLELinear):
113:                 expert_masks = torch.tensor(
114:                     [
115:                         1 if expert_id in task_ids else 0
116:                         for expert_id in layer.expert_ids
117:                     ],
118:                     dtype=torch.bool,
119:                 )
120:                 layer.set_expert_masks(expert_masks)
121: 
122:     def freeze_old_experts(self, task_id):
123:         adapter_name = self.active_adapters[0]
124:         for _, layer in self.named_modules():
125:             if isinstance(layer, DMoLELinear):
126:                 for i, expert_id in enumerate(layer.expert_ids):
127:                     if expert_id != task_id:
128:                         layer.lora_A[adapter_name][i].requires_grad_(False)
129:                         layer.lora_B[adapter_name][i].requires_grad_(False)

internvl/dmole/layer.py:151-179
151:     def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
152:         result = self.base_layer(x, *args, **kwargs)
153:         batch_size, sequence_length, hidden_dim = x.shape
154:         input_dtype = x.dtype
155: 
156:         self.expert_masks = self.expert_masks.to(x.device)
157: 
158:         for adapter_name in self.active_adapters:
159:             final_hidden_states = torch.zeros(
160:                 (batch_size, sequence_length, self.out_features),
161:                 device=x.device,
162:                 dtype=input_dtype,
163:             )
164: 
165:             selected_experts = torch.where(self.expert_masks)[0]
166: 
167:             for expert_idx in selected_experts:
168:                 expert_lora_A = self.lora_A[adapter_name][expert_idx]
169:                 expert_lora_B = self.lora_B[adapter_name][expert_idx]
170: 
171:                 current_hidden_states = expert_lora_B(
172:                     expert_lora_A(self.lora_dropout[adapter_name](x))
173:                 )
174: 
175:                 final_hidden_states += current_hidden_states
176: 
177:             result += final_hidden_states * self.scaling[adapter_name]
178: 
179:         return result

internvl/dmole/layer.py:190-196
190:                 nn.init.zeros_(self.lora_B[adapter_name][i].weight)
191: 
192:     def disable_lora(self):
193:         self.disable = True
194: 
195:     def enable_lora(self):
196:         self.disable = False

internvl/train/trainer.py:116-167
116:         # get current task_id
117:         if hasattr(model, "module"):
118:             real_model = model.module
119:             current_task_id = model.module.config.task_id
120:         else:
121:             real_model = model
122:             current_task_id = model.config.task_id
123: 
124:         if current_task_id is not None:
125:             try:
126:                 # Set no experts for sequence representation computation
127:                 if hasattr(model, "module"):
128:                     model.module.set_expert_masks([])
129:                 else:
130:                     model.set_expert_masks([])
131: 
132:                 # create a copy of inputs for processing, avoid modifying the original data
133:                 inputs_copy = {k: v for k, v in inputs.items()}
134:                 if labels is not None:
135:                     inputs_copy["labels"] = labels  # restore labels for process_inputs
136: 
137:                 new_inputs = process_inputs(inputs_copy, real_model, self.tokenizer)
138: 
139:                 # get sequence representations
140:                 if hasattr(model, "module"):
141:                     seq_reps = model.module.extract_sequence_feature(**new_inputs)
142:                     task_ids = model.module.get_task_ids(
143:                         seq_reps, mode="training", current_task_id=current_task_id
144:                     )
145:                     model.module.set_expert_masks(task_ids)
146:                 else:
147:                     seq_reps = model.extract_sequence_feature(**new_inputs)
148:                     task_ids = model.get_task_ids(
149:                         seq_reps, mode="training", current_task_id=current_task_id
150:                     )
151:                     model.set_expert_masks(task_ids)
152: 
153:                 logger.info(
154:                     f"Training: Selected task ids: {task_ids} (current task: {current_task_id})"
155:                 )
156: 
157:             except Exception as e:
158:                 rank0_print(
159:                     f"DMoLE processing failed: {e}, falling back to current task only"
160:                 )
161:                 # if error, use current task only
162:                 if hasattr(model, "module"):
163:                     model.module.set_expert_masks([current_task_id])
164:                 else:
165:                     model.set_expert_masks([current_task_id])
166:         # === end of DMoLE logic ===
167: 

internvl/train/internvl_chat_finetune.py:343-358
343:     if model_args.freeze_mlp:
344:         _freeze_params(model.mlp1)
345: 
346:     if model_args.unfreeze_vit_layers != 0:
347:         layers = model.vision_model.encoder.layers[model_args.unfreeze_vit_layers :]
348:         for k, v in layers.named_parameters():
349:             logger.info(f"Unfreezing ViT layer: {k}")
350:             v.requires_grad = True
351: 
352:     if model_args.use_dmole:
353:         if model_args.use_llm_lora:
354:             model.language_model.set_expert_masks(model_args.task_id)
355:             model.language_model.freeze_old_experts(model_args.task_id)
356:         if model_args.use_backbone_lora:
357:             model.vision_model.set_expert_masks(model_args.task_id)
358:             model.vision_model.freeze_old_experts(model_args.task_id)

scripts/preprocess/train_autoencoder.py:100-125
100:     """create the reconstruction loss quantile table"""
101:     quantiles = [0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99]
102: 
103:     # store the results
104:     results = {}
105: 
106:     for folder in folders:
107:         print(f"Computing reconstruction losses for {folder}...")
108: 
109:         # compute the reconstruction loss
110:         current_losses = autoencoders[folder].compute_reconstruction_loss(
111:             embeddings[folder]
112:         )
113: 
114:         # compute the quantiles
115:         quantile_values = torch.quantile(current_losses, torch.tensor(quantiles).cuda())
116: 
117:         # store the results
118:         results[folder] = {
119:             f"Q{int(q*100)}": val.item() for q, val in zip(quantiles, quantile_values)
120:         }
121: 
122:         results[folder]["mean"] = current_losses.mean().item()
123:         results[folder]["std"] = current_losses.std().item()
124:         results[folder]["min"] = current_losses.min().item()
125:         results[folder]["max"] = current_losses.max().item()

scripts/preprocess/train_autoencoder.py:196-205
196: print("\nCreating reconstruction loss quantile table...")
197: quantile_table = create_reconstruction_loss_quantile_table(
198:     embeddings, autoencoders, folders
199: )
200: 
201: # save the quantile table
202: output_path = f"autoencoder_models/reconstruction_loss_quantiles.csv"
203: quantile_table.to_csv(output_path)
204: print(f"Reconstruction loss quantile table saved to: {output_path}")
205: 

scripts/train/dmole.sh:27-37
27:   "vizwiz_caption:./shell/dmole/vizwiz_caption.json:10:1"
28:   "skvg:./shell/dmole/skvg.json:10:5"
29:   "textcaps:./shell/dmole/textcaps.json:10:1"
30:   "iconqa:./shell/dmole/iconqa.json:10:1"
31:   "ocrvqa:./shell/dmole/ocrvqa.json:8:1"
32:   "flickr30k:./shell/dmole/flickr30k.json:10:1"
33:   "vizwiz:./shell/dmole/vizwiz.json:10:5"
34:   "kvqa:./shell/dmole/kvqa.json:10:1"
35:   "pmcvqa:./shell/dmole/pmcvqa.json:10:1"
36: )
37: 

scripts/train/dmole.sh:100-112
100:     --use_backbone_lora 8 \
101:     --use_dmole True \
102:     --dmole_arch_path ${DMOLE_ARCH_PATH} \
103:     --autoencoder_path autoencoder_models \
104:     --task_id $((i+1)) \
105:     --vision_select_layer -1 \
106:     --dataloader_num_workers 4 \
107:     --bf16 True \
108:     --num_train_epochs ${EPOCHS} \
109:     --per_device_train_batch_size ${BATCH_SIZE} \
110:     --gradient_accumulation_steps 1 \
111:     --evaluation_strategy "no" \
112:     --save_strategy "steps" \

scripts/train/seq_lora.sh:90-101
90:     --max_dynamic_patch 6 \
91:     --down_sample_ratio 0.5 \
92:     --drop_path_rate 0.0 \
93:     --freeze_llm True \
94:     --freeze_mlp True \
95:     --freeze_backbone True \
96:     --use_llm_lora 4 \
97:     --use_backbone_lora 4 \
98:     --vision_select_layer -1 \
99:     --dataloader_num_workers 4 \
100:     --bf16 True \
101:     --num_train_epochs ${EPOCHS} \

run_eval.sh:28-39
28: # Task configuration: "task_name:evaluation_dataset:batch_size"
29: TASKS=(
30:   "vizwiz_caption:caption-vizwiz-val:16"
31:   "skvg:grouding-skvg-test:8"
32:   "textcaps:caption-textcaps-val:8"
33:   "iconqa:vqa-iconqa-test:8"
34:   "ocrvqa:vqa-ocrvqa-val:8"
35:   "flickr30k:caption-flickr30k:8"
36:   "vizwiz:vqa-vizwiz-val:8"
37:   "kvqa:vqa-kvqa-test:16"
38:   "pmcvqa:vqa-pmcvqa-test-clean:8" 
39: )

run_eval.sh:87-90
87:   for task_idx in "${task_indices[@]}"; do
88:     IFS=: read -r task_name dataset batch <<< "${TASKS[$task_idx]}"           # Parse task config: name:dataset:batch_size
89:     echo "Evaluating $(basename "$model") on $dataset"
90:     GPUS=$GPUS bash evaluate.sh "$model" "$dataset" --dynamic --batch-size "$batch" 2>&1 | tee -a "$LOG_FILE"

eval/vqa/evaluate_vqa.py:397-422
397:             questions,
398:             question_ids,
399:             annotations,
400:             num_patches_list,
401:         ) in enumerate(tqdm(dataloader)):
402:             pixel_values = pixel_values.to(torch.bfloat16).cuda()
403:             generation_config = dict(
404:                 num_beams=args.num_beams,
405:                 max_new_tokens=ds_collections[ds_name]["max_new_tokens"],
406:                 min_new_tokens=1,
407:                 do_sample=True if args.temperature > 0 else False,
408:                 temperature=args.temperature,
409:             )
410:             preds = model.batch_chat(
411:                 tokenizer=tokenizer,
412:                 pixel_values=pixel_values,
413:                 questions=questions,
414:                 generation_config=generation_config,
415:                 num_patches_list=num_patches_list,
416:                 # verbose=True,
417:             )
418:             answers = preds
419: 
420:             for question, question_id, answer, annotation in zip(
421:                 questions, question_ids, answers, annotations
422:             ):

eval/vqa/evaluate_vqa.py:590-599
590:     parser.add_argument("--checkpoint", type=str, default="")
591:     parser.add_argument(
592:         "--datasets",
593:         type=str,
594:         default="okvqa_val,textvqa_val,vizwiz_val,ai2diagram_test,gqa_testdev_llava",
595:     )
596:     parser.add_argument("--batch-size", type=int, default=8)
597:     parser.add_argument("--num-workers", type=int, default=1)
598:     parser.add_argument("--num-beams", type=int, default=1)
599:     parser.add_argument("--temperature", type=float, default=0.0)

eval/caption/evaluate_caption.py:202-218
202:             generation_config = dict(
203:                 num_beams=args.num_beams,
204:                 max_new_tokens=ds_collections[ds_name]["max_new_tokens"],
205:                 min_new_tokens=ds_collections[ds_name]["min_new_tokens"],
206:                 do_sample=True if args.temperature > 0 else False,
207:                 temperature=args.temperature,
208:             )
209:             preds = model.batch_chat(
210:                 tokenizer=tokenizer,
211:                 pixel_values=pixel_values,
212:                 num_patches_list=num_patches_list,
213:                 questions=[prompt] * len(pixel_values),
214:                 generation_config=generation_config,
215:                 verbose=True,
216:             )
217:             image_ids.extend(ids)
218:             captions.extend(preds)

eval/caption/evaluate_caption.py:280-287
280: 
281: if __name__ == "__main__":
282:     parser = argparse.ArgumentParser()
283:     parser.add_argument("--checkpoint", type=str, default="")
284:     parser.add_argument("--datasets", type=str, default="coco,flickr30k,nocaps")
285:     parser.add_argument("--batch-size", type=int, default=10)
286:     parser.add_argument("--num-workers", type=int, default=1)
287:     parser.add_argument("--num-beams", type=int, default=1)

eval/refcoco/evaluate_grounding.py:171-190
171:         for _, (pixel_values, questions, bboxes, hws, num_patches_list) in enumerate(
172:             tqdm(dataloader)
173:         ):
174:             pixel_values = pixel_values.to(torch.bfloat16).cuda()
175:             generation_config = dict(
176:                 num_beams=args.num_beams,
177:                 max_new_tokens=100,
178:                 min_new_tokens=1,
179:                 do_sample=True if args.temperature > 0 else False,
180:                 temperature=args.temperature,
181:             )
182:             preds = model.batch_chat(
183:                 tokenizer=tokenizer,
184:                 pixel_values=pixel_values,
185:                 questions=questions,
186:                 num_patches_list=num_patches_list,
187:                 generation_config=generation_config,
188:                 verbose=True,
189:             )
190:             answers = preds

eval/refcoco/evaluate_grounding.py:272-279
272:         type=str,
273:         default="refcoco_val,refcoco_testA,refcoco_testB,"
274:         "refcoco+_val,refcoco+_testA,refcoco+_testB,"
275:         "refcocog_val,refcocog_test,skvg_test",
276:     )
277:     parser.add_argument("--batch-size", type=int, default=10)
278:     parser.add_argument("--num-workers", type=int, default=1)
279:     parser.add_argument("--num-beams", type=int, default=1)