1from transformers import LlamaModel, LlamaPreTrainedModel, TextClassificationPipeline
2from torch import nn
3import torch
4from typing import Dict
56classAtheneForSequenceClassification(LlamaPreTrainedModel):7def__init__(self, config):8super().__init__(config)9 self.model = LlamaModel(config)10 self.v_head = nn.Linear(config.hidden_size,1, bias=False)11 self.CLS_ID =12800312# Initialize weights and apply final processing13 self.post_init()1415defget_device(self):16return self.model.device
1718defforward(19 self,20 input_ids=None,21 past_key_values=None,22 attention_mask=None,23 position_ids=None,24):25 transformer_outputs = self.model(26 input_ids,27 attention_mask=attention_mask,28 position_ids=position_ids,29 output_hidden_states=True,30)31 hidden_states = transformer_outputs.hidden_states[-1]32 scores =[]33 rewards = self.v_head(hidden_states).squeeze(-1)3435 bs =int(input_ids.shape[0])3637for i inrange(bs):38 c_inds =(input_ids[i]== self.CLS_ID).nonzero()39 c_ind = c_inds[-1].item()40 scores.append(rewards[i, c_ind])41 scores = torch.stack(scores)42return{"scores": scores}4344# Make a pipeline to handle pre and post-processing45classAtheneRewardPipeline(TextClassificationPipeline):4647defpreprocess(self, inputs,**tokenizer_kwargs)-> Dict[str, torch.Tensor]:48 return_tensors = self.framework
4950 formatted = self.tokenizer.apply_chat_template(inputs, tokenize=False)5152 formatted = formatted + self.tokenizer.cls_token
5354return self.tokenizer(55 formatted,56 return_tensors=return_tensors,57 max_length=4096,58 padding="longest",59 truncation=True,60)6162defpostprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True):63return model_outputs["scores"].cpu().float().item()6465# Initialize the model66model = AtheneForSequenceClassification.from_pretrained("Nexusflow/Athene-RM-8B", torch_dtype=bfloat16)67tokenizer = AutoTokenizer.from_pretrained("Nexusflow/Athene-RM-8B")6869# Initialize the pipeline70pipe = pipeline(71 task="text-classification",72 model=self.model,73 tokenizer=self.tokenizer,74 pipeline_class=AtheneRewardPipeline,75 device_map="auto",76)7778messages =[79{80"role":'user',81"content":"What is an Athene Noctura? Explain one sentence."82},83{84"role":"assistant",85"content":"The Athene noctua, also known as the little owl, is a small, nocturnal owl species native to Europe, Asia, and North Africa, characterized by its distinctive facial disk and piercing yellow eyes."86}87]8889print(pipe([messages]))# Print the reward!90
Citation
@misc{Athene2024,
title = {Athene-70B: Redefining the Boundaries of Post-Training for Open Models},
url = {https://nexusflow.ai/blogs/athene},
author = {Frick, Evan and Jin, Peter and Li, Tianle and Ganesan, Karthik and Zhang, Jian and Jiao, Jiantao and Zhu, Banghua},
month = {July},
year = {2024}
}