
FILE code/training/pref_arm_trainer.py
60:             The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively.
61:         """
62:         pi_logratios = policy_chosen_logps - policy_rejected_logps
63:         gamma_logratios = self.gamma / beta 
64:         pi_logratios = pi_logratios.to(self.accelerator.device)
65:         logits = pi_logratios - gamma_logratios
66: 
67:         if self.loss_type == "sigmoid":
68:             losses = (
69:                 -F.logsigmoid(beta * logits) * (1 - self.label_smoothing)
70:                 - F.logsigmoid(-beta * logits) * self.label_smoothing
71:             )
72:         elif self.loss_type == "hinge":
145: 
146:         for n, p in model.named_parameters():
147:             if 'pref_vec' in n:
148:                 p.data = preference.to(p.device)
149:                 p.requires_grad = False
162:         obj_len = bs // len(self.obj_key)
163:         for obj_idx, obj in enumerate(self.obj_key):
164:             chosen_idx = [batch['labels'][i][obj] for i in range(bs)]
165:             rejected_idx = [1 - batch['labels'][i][obj] for i in range(bs)]
166: 
167:             obj_policy_rejected_logps = concat_logps[range(bs), rejected_idx]
168:             obj_policy_chosen_logps = concat_logps[range(bs), chosen_idx]
169:             obj_policy_rejected_logits = concat_logits[range(bs), rejected_idx]
170:             obj_policy_chosen_logits = concat_logits[range(bs), chosen_idx]
171: 
172:             losses, chosen_rewards, rejected_rewards = self.arm_loss(
173:                 self.beta_obj[obj_idx],
174:                 obj_policy_chosen_logps,
175:                 obj_policy_rejected_logps
176:             )
187:             # metrics[f"{prefix}rewards_{obj}/margins"] = (chosen_rewards - rejected_rewards).mean().cpu()
188:             # metrics[f"{prefix}logps_{obj}/rejected"] = obj_policy_rejected_logps.detach().mean().cpu()
189:             # metrics[f"{prefix}logps_{obj}/chosen"] = obj_policy_chosen_logps.detach().mean().cpu()
190:             # metrics[f"{prefix}logits_{obj}/rejected"] = obj_policy_rejected_logits.detach().mean().cpu()
191:             # metrics[f"{prefix}logits_{obj}/chosen"] = obj_policy_chosen_logits.detach().mean().cpu()
192: 
193:         total_loss = sum([each_loss*each_pref for each_loss, each_pref in zip(loss_list, preference)])

FILE code/training/train_pref_arm.py
137: 
138:     def return_prompt_and_responses(sample, obj_key) -> Dict[str, str]:
139:         labels = {'safe': sample['safer_response_id'], 
140:                 "help": sample['better_response_id'],}
141:         return {
142:             "prompt": format_prompt_pku_safe_rlhf(input=sample["prompt"], eos_token='Not used'),

FILE code/data/relabel.py
36:             new_d[f'harm_score_{idx}'] = model_harmless(**input_ids)['end_scores'][0][0].item()
37:         
38:         new_d['better_response_id'] = 0 if new_d['help_score_0'] > new_d['help_score_1'] else 1
39:         new_d['safer_response_id'] = 0 if new_d['harm_score_0'] < new_d['harm_score_1'] else 1
40: 
41:         new_dataset.append(new_d)

FILE code/evaluation/generate_outputs.py
64: 
65:     model_parser.add_argument(
66:         '--max_new_tokens',
67:         type=int,
68:         default=512,
138:     
139:     model = ModelArithmetic(formula, max_length = args.max_length) 
140:     temperature = 0
141: 
142:     return model, tokenizer, temperature
159:         data_evaluation = json.load(f)
160: 
161:     ##### change pref_vec_init for reward ####
162:     cache_path = os.path.join(args.cache_dir, model_name)
163:     os.makedirs(cache_path, exist_ok=True)
165:         config = json.load(f)
166: 
167:     config['pref_vec_init'] = [args.alpha_harmlessness, args.alpha_helpfulness]
168: 
169:     with open(f'{cache_path}/adapter_config.json', 'w', encoding='utf-8') as f:
173: 
174:     ##################### Load models #####################
175:     model, tokenizer, temperature = get_model_arithmetic(model_pth_base=args.model_base_name_or_path, 
176:                     model_pth_reward_both=cache_path,
177:                     args=args)
179:     if args.normalize_logit:
180:         print('\nEnforcing temperature=1.0 in the model_arithmetic generation; The logit weights of base models and potential ARMs are normalized.\n')
181:         temperature = 1.0
182:     # generate function will remove eos token
183:     generate = lambda prompt: model.generate_text(prompt, max_new_tokens=args.max_new_tokens, batch_size=None, temperature=temperature, top_p=1, top_k=0, do_speculation=False)[0].removesuffix(tokenizer.eos_token)
184: 
185:     if args.normalize_logit:

FILE code/evaluation/compute_reward.py

FILE peft/src/peft/utils/save_and_load.py
97:                 to_return = model.resize_state_dict_by_rank_pattern(rank_pattern, to_return, adapter_name)
98: 
99:     elif config.peft_type in (PeftType.PBLORA):
100:         bias = config.bias
101:         if bias == "none":
102:             to_return = {k: state_dict[k] for k in state_dict if "pblora_" in k}
103:         elif bias == "all":
104:             to_return = {k: state_dict[k] for k in state_dict if "pblora_" in k or "bias" in k}
105:         elif bias == "lora_only":
106:             to_return = {}
107:             for k in state_dict:
108:                 if "pblora_" in k:
109:                     to_return[k] = state_dict[k]
110:                     bias_name = k.split("pblora_")[0] + "bias"
111:                     if bias_name in state_dict:
112:                         to_return[bias_name] = state_dict[bias_name]
113:         else:
114:             raise NotImplementedError
115:         to_return = {k: v for k, v in to_return.items() if (("pblora_" in k and adapter_name in k) or ("bias" in k))}
116: 
117:     elif config.peft_type == PeftType.LOHA:
234:         PeftType.OFT,
235:         PeftType.POLY,
236:         PeftType.PBLORA,
237:     ):
238:         peft_model_state_dict = {}
245:             PeftType.OFT: "oft_",
246:             PeftType.POLY: "poly_",
247:             PeftType.PBLORA: "pblora_",
248:         }[config.peft_type]
249:         for k, v in state_dict.items():

FILE language-model-arithmetic/src/model_arithmetic/model_arithmetic.py
25:     _supports_sdpa = True
26: 
27:     def __init__(self, formula : Operator, default_model : str = None, dtype=torch.bfloat16, intermediate_argmax : bool = False, epsilon = 1e-6, 
28:                  retroactive_operators = [], calculate_statistics=True, needs_input_tokens_lm_eval=False, lm_eval_task=None, tokenizer=None, max_length=None):
29:         """Initializes the prompt arithmetic model.
33:             default_model (str, optional): Default model for RunnableOperators that don't have a model associated with them. Defaults to None.
34:             dtype (torch.dtype, optional): Dtype of the models to load by default. Defaults to torch.bfloat16.
35:             intermediate_argmax (bool, optional): Something unimportant that was tried out, but now deprecated. Defaults to False.
36:             epsilon (float, optional): Just some small value. Defaults to 1e-12.
37:             retroactive_operators (list, optional): The retroactive operators that need to be applied. Defaults to [].
52:         self.output_type = namedtuple("ModelArithmeticOutput", ["logits", "logprobs_per_model"])
53:         self.logits_type = namedtuple("ModelArithmeticLogits", ["logits"])
54:         self.intermediate_argmax = intermediate_argmax
55:         self.retroactive_operators = retroactive_operators
56:         self.calculate_statistics = calculate_statistics
314:             torch.tensor: Logprobs for each token in each sample
315:         """
316:         if temperature == 0:
317:             logprobs_argmax = torch.argmax(logprobs, dim=-1)
318:             logprobs = torch.nn.functional.one_hot(logprobs_argmax, num_classes=logprobs.shape[-1]).float()
319:             return logprobs
320:         logprobs = logprobs / temperature
457:                 new_model_probs = self.process_logprobs(group_model_history)
458:                 
459:                 if self.intermediate_argmax and not self.formula.is_finished(group_model_history):
460:                     argmax_el = torch.argmax(new_model_probs)
461:                     new_model_probs = torch.zeros_like(new_model_probs)
462:                     new_model_probs[argmax_el] = 1.0
463:                 
464:                 if do_speculation_sample:
739:         torch.cuda.empty_cache()
740: 
741:     def generate_text(self, sentences, max_new_tokens=1024, stop_texts=None, batch_size=None,
742:                  temperature=1.0, top_p=1.0, top_k=0, num_return_sequences=1, do_speculation=False, use_cache=True, **kwargs):
743:         """Generates text based on the input params
745:         Args:
746:             sentences (list[str]): List of input sentences
747:             max_new_tokens (int, optional): Max generation length. Defaults to 1024.
748:             stop_texts (list[str], optional): Strings at which to stop generation. Defaults to None.
749:             batch_size (int, optional): Batch size. Defaults to None (all at once).
807:             for i in range(len(current_indices)):
808:                 sentences[current_indices[i]] = start_sentences[current_indices[i]] + generated_texts[current_indices[i]]
809:                 if any([stop_text in generated_texts[current_indices[i]] for stop_text in stop_texts]) or len(generated_tokens[current_indices[i]]) >= max_new_tokens:
810:                     if len(self.model_prediction_history[i]) == 0:
811:                         indices_to_remove.append(i)
846:         return generated_texts
847: 
848:     def generate(self, input_ids, attention_mask=None, do_sample=False, max_new_tokens=1024, 
849:                  stopping_criteria=None, temperature=1.0, top_p=1.0, top_k=0, use_cache=True, eos_token_id=None, pad_token_id=None, **kwargs):
850:         """Generates text based on the input params. Needed for compatibility with lm-evaluation-harness
854:             attention_mask (torch.tensor, optional): attention mask. Defaults to None.
855:             do_sample (bool, optional): Whether or not to sample. Defaults to False.
856:             max_new_tokens (int, optional): Max new number of tokens. Defaults to 128.
857:             stopping_criteria (_type_, optional): Stopping criteria to use. Defaults to None.
858:             temperature (float, optional): Temperature to. Defaults to 1.0.
877:             stopping_sequences += [self.tokenizer.decode([eos_token_id])]
878:             
879:         texts = self.generate_text(input_texts, max_new_tokens=max_new_tokens, stop_texts=stopping_sequences,
880:                                     batch_size=batch_size, temperature=temperature, top_p=top_p, top_k=top_k, use_cache=use_cache)
881:         encoded_texts = self.tokenizer.batch_encode_plus(texts, add_special_tokens=False, return_tensors="pt").input_ids.to(self.device)

FILE language-model-arithmetic/src/model_arithmetic/runnable_operators.py
430:             n_new_tokens (int): Number of new tokens since last run
431:         """
432:         max_new_tokens = max(n_new_tokens)
433:         past_key_values = None
434:         if self.cache is not None and self.enable_cache:
435:             input_ids = input_ids[:, -max_new_tokens:]
436:             if self.run_eager:
437:                 past_key_values = self.cache
438:             else:
439:                 past_key_values = self.pad_cache(
440:                     [self.select_from_sample_cache(self.cache[i], until=-max_new_tokens + n_new_tokens[i]) if max_new_tokens > n_new_tokens[i] else self.cache[i]
441:                     for i in range(len(n_new_tokens))],
442:                     attention_mask.shape[1] - max_new_tokens
443:                 )
444:         return {
514:             except RuntimeError as e:
515:                 raise RuntimeError(f"Error thrown when running model. This is probably caused because the model handles the key-value cache differently. Consider setting dim_values_past and dim_keys_past values or disabling the key-value cache. Alternatively, you can set run_eager=True, but this feature is incompatible with speculative sampling and some other features.")
516:             logprobs = torch.log_softmax(model_output.logits[:, :, :self.tokenizer_length], dim=-1)
517:         
518:         if self.enable_cache and use_cache:
788:         
789:         if not self.minimize:
790:             model_outputs_logprobs = torch.log_softmax(model_outputs, dim=-1)[:, self.index]
791:         elif self.minimize and model_outputs.shape[1] == 2:
792:             model_outputs_logprobs = torch.log_softmax(model_outputs, dim=-1)[:, 1 - self.index]
793:         else:
794:             model_output_probs = torch.softmax(model_outputs, dim=-1)[:, self.index]
811:         
812:         if not self.use_bayes:
813:             output_logprobs = torch.log_softmax(output_logprobs, dim=-1)
814:                 
815:         