Upload representation-trained ScanFlow checkpoint
Browse filesFiles changed (13)
- config.jsonAdded+132
- configuration_deepseek_v2.pyAdded+210
- conversation.pyAdded+280
- deepencoderv2.pyAdded+1956
- generation_config.jsonAdded+6
- model-00001-of-00002.safetensorsAdded+3
- model-00002-of-00002.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_deepseekocr2.pyAdded+2110
- modeling_deepseekv2.pyAdded+1998
- special_tokens_map.jsonAdded+27
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132{ "_name_or_path": "/home/krisxu/scratch/2026_summer_research_project/CueFlow/output/scanflow_plan1_recurrent_attention/v8-20260818-033505/scanflowpro_v2", "architectures": [ "DeepseekOCR2ForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "modeling_deepseekocr2.DeepseekOCR2Config", "AutoModel": "modeling_deepseekocr2.DeepseekOCR2ForCausalLM" }, "aux_loss_alpha": 0.001, "bos_token_id": 0, "candidate_resolutions": [ [ 1024, 1024 ] ], "eos_token_id": 1, "ep_size": 1, "first_k_dense_replace": 1, "global_view_pos": "head", "hidden_act": "silu", "hidden_size": 1280, "initializer_range": 0.02, "intermediate_size": 6848, "kv_lora_rank": null, "language_config": { "architectures": [ "DeepseekV2ForCausalLM" ], "auto_map": { "AutoConfig": "configuration_deepseekv2.DeepseekV2Config", "AutoModel": "modeling_deepseek.DeepseekV2Model", "AutoModelForCausalLM": "modeling_deepseek.DeepseekV2ForCausalLM" }, "bos_token_id": 0, "eos_token_id": 1, "first_k_dense_replace": 1, "hidden_size": 1280, "intermediate_size": 6848, "kv_lora_rank": null, "lm_head": true, "max_position_embeddings": 8192, "moe_intermediate_size": 896, "n_group": 1, "n_routed_experts": 64, "n_shared_experts": 2, "num_attention_heads": 10, "num_experts_per_tok": 6, "num_hidden_layers": 12, "num_key_value_heads": 10, "q_lora_rank": null, "qk_nope_head_dim": 0, "qk_rope_head_dim": 0, "rm_head": false, "topk_group": 1, "topk_method": "greedy", "torch_dtype": "bfloat16", "use_mla": false, "v_head_dim": 0, "vocab_size": 129280 }, "lm_head": true, "max_position_embeddings": 8192, "model_type": "DeepseekOCR2", "moe_intermediate_size": 896, "moe_layer_freq": 1, "n_group": 1, "n_routed_experts": 64, "n_shared_experts": 2, "norm_topk_prob": false, "num_attention_heads": 10, "num_experts_per_tok": 6, "num_hidden_layers": 12, "num_key_value_heads": 10, "pad_token_id": 2, "pretraining_tp": 1, "projector_config": { "input_dim": 896, "model_type": "mlp_projector", "n_embed": 1280, "projector_type": "linear" }, "q_lora_rank": null, "qk_nope_head_dim": 0, "qk_rope_head_dim": 0, "rm_head": false, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 10000.0, "routed_scaling_factor": 1.0, "scoring_func": "softmax", "seq_aux": true, "tie_word_embeddings": false, "tile_tag": "2D", "topk_group": 1, "topk_method": "greedy", "torch_dtype": "bfloat16", "transformers_version": "4.46.3", "use_cache": false, "use_mla": false, "v_head_dim": 0, "vision_config": { "image_size": 1024, "mlp_ratio": 3.7362, "model_name": "deepencoderv2", "model_type": "vision", "width": { "qwen2-0-5b": { "dim": 896 }, "sam_vit_b": { "downsample_channels": [ 512, 1024 ], "global_attn_indexes": [ 2, 5, 8, 11 ], "heads": 12, "layers": 12, "width": 768 } } }, "vocab_size": 129280}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}class DeepseekV2Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DeepSeek-V2 with multi-latent attention.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 102400): Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DeepseekV2Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 11008): Dimension of the MLP representations. moe_intermediate_size (`int`, *optional*, defaults to 1407): Dimension of the MoE representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. n_shared_experts (`int`, *optional*, defaults to None): Number of shared experts, None means dense model. n_routed_experts (`int`, *optional*, defaults to None): Number of routed experts, None means dense model. routed_scaling_factor (`float`, *optional*, defaults to 1.0): Scaling factor or routed experts. topk_method (`str`, *optional*, defaults to `gready`): Topk method used in routed gate. n_group (`int`, *optional*, defaults to None): Number of groups for routed experts. topk_group (`int`, *optional*, defaults to None): Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups). num_experts_per_tok (`int`, *optional*, defaults to None): Number of selected experts, None means dense model. moe_layer_freq (`int`, *optional*, defaults to 1): The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers. first_k_dense_replace (`int`, *optional*, defaults to 0): Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head). \--k dense layers--/ norm_topk_prob (`bool`, *optional*, defaults to False): Whether to normalize the weights of the routed experts. scoring_func (`str`, *optional*, defaults to 'softmax'): Method of computing expert weights. aux_loss_alpha (`float`, *optional*, defaults to 0.001): Auxiliary loss weight coefficient. seq_aux = (`bool`, *optional*, defaults to True): Whether to compute the auxiliary loss for each individual sample. num_key_value_heads (`int`, *optional*): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. pretraining_tp (`int`, *optional*, defaults to 1): Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is necessary to ensure exact reproducibility of the pretraining results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232). tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update `max_position_embeddings` to the expected new maximum. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. use_mla (`bool`, *optional*, defaults to `True`): Use multi-latent attention or multi-head attention. If True, the model will use multi-latent attention, otherwise, it will use multi-head attention.
```python >>> from transformers import DeepseekV2Model, DeepseekV2Config
>>> # Initializing a Deepseek-V2 style configuration >>> configuration = DeepseekV2Config()
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "deepseek_v2" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size=102400, hidden_size=4096, intermediate_size=11008, moe_intermediate_size = 1407, num_hidden_layers=30, num_attention_heads=32, num_key_value_heads=32, n_shared_experts = None, n_routed_experts = None, ep_size = 1, routed_scaling_factor = 1.0, kv_lora_rank = 512, q_lora_rank = 1536, qk_rope_head_dim = 64, v_head_dim = 128, qk_nope_head_dim = 128, topk_method = 'gready', n_group = None, topk_group = None, num_experts_per_tok = None, moe_layer_freq = 1, first_k_dense_replace = 0, norm_topk_prob = False, scoring_func = 'softmax', aux_loss_alpha = 0.001, seq_aux = True, hidden_act="silu", max_position_embeddings=2048, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=100000, eos_token_id=100001, pretraining_tp=1, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, attention_dropout=0.0, use_mla=True, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.moe_intermediate_size = moe_intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.n_shared_experts = n_shared_experts self.n_routed_experts = n_routed_experts self.ep_size = ep_size self.routed_scaling_factor = routed_scaling_factor self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.topk_method = topk_method self.n_group = n_group self.topk_group = topk_group self.num_experts_per_tok = num_experts_per_tok self.moe_layer_freq = moe_layer_freq self.first_k_dense_replace = first_k_dense_replace self.norm_topk_prob = norm_topk_prob self.scoring_func = scoring_func self.aux_loss_alpha = aux_loss_alpha self.seq_aux = seq_aux # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = float(rms_norm_eps) self.pretraining_tp = pretraining_tp self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.use_mla = use_mla
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""From https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py"""
import dataclassesfrom enum import IntEnum, autofrom typing import Any, Dict, List
class SeparatorStyle(IntEnum): """Separator styles."""
DeepSeek = auto() DeepSeekV2 = auto() PLAIN = auto() ALIGNMENT = auto()
@dataclasses.dataclassclass Conversation: """A class that manages prompt templates and keeps all conversation history."""
# The name of this template name: str # The template of the system prompt system_template: str = "{system_message}" # The system message system_message: str = "" # The names of two roles roles: List[str] = (("USER", "ASSISTANT"),) # All messages. Each item is (role, message). messages: List[List[str]] = () # The number of few shot examples offset: int = 0 # The separator style and configurations sep_style: SeparatorStyle = SeparatorStyle.DeepSeek sep: str = "\n" sep2: str = None # Stop criteria (the default one is EOS token) stop_str: str = None # Stops generation if meeting any token in this list stop_token_ids: List[int] = None
def get_prompt(self) -> str: """Get the prompt for generation.""" system_prompt = self.system_template.format(system_message=self.system_message) if self.sep_style == SeparatorStyle.DeepSeek: seps = [self.sep, self.sep2] if system_prompt == "" or system_prompt is None: ret = "" else: ret = system_prompt + seps[0] for i, (role, message) in enumerate(self.messages): if message: ret += role + ": " + message + seps[i % 2] else: ret += role + ":" return ret elif self.sep_style == SeparatorStyle.DeepSeekV2: seps = [self.sep, self.sep2] if system_prompt == "" or system_prompt is None: ret = "" else: ret = system_prompt + seps[0] for i, (role, message) in enumerate(self.messages): if message: if role == "User": ret += "<|sft▁begin|>\n" + message + self.sep #<|sft▁begin|>User Input<|sft▁end|>\nResponse<|end▁of▁sentence|> else: ret += message + self.sep2 else: ret = ret return ret
elif self.sep_style == SeparatorStyle.PLAIN: seps = [self.sep, self.sep2] ret = "" for i, (role, message) in enumerate(self.messages): if message: if type(message) is tuple: message, _, _ = message if i % 2 == 0: ret += message + seps[i % 2] else: ret += message + seps[i % 2] else: ret += "" return ret elif self.sep_style == SeparatorStyle.ALIGNMENT: seps = [self.sep, self.sep2] ret = "" for i, (role, message) in enumerate(self.messages): if message: if type(message) is tuple: message, _, _ = message if i % 2 == 0: ret += '<image>\n' + seps[i % 2] else: ret += message + seps[i % 2] else: ret += "" return ret else: raise ValueError(f"Invalid style: {self.sep_style}")
def set_system_message(self, system_message: str): """Set the system message.""" self.system_message = system_message
def append_message(self, role: str, message: str): """Append a new message.""" self.messages.append([role, message])
def update_last_message(self, message: str): """Update the last output.
The last message is typically set to be None when constructing the prompt, so we need to update it in-place after getting the response from a model. """ self.messages[-1][1] = message
def reset_message(self): """Reset a new message.""" self.messages = []
def to_gradio_chatbot(self): """Convert the conversation to gradio chatbot format.""" ret = [] for i, (role, msg) in enumerate(self.messages[self.offset :]): if i % 2 == 0: ret.append([msg, None]) else: ret[-1][-1] = msg return ret
def to_openai_api_messages(self): """Convert the conversation to OpenAI chat completion format.""" system_prompt = self.system_template.format(system_message=self.system_message) ret = [{"role": "system", "content": system_prompt}]
for i, (_, msg) in enumerate(self.messages[self.offset :]): if i % 2 == 0: ret.append({"role": "user", "content": msg}) else: if msg is not None: ret.append({"role": "assistant", "content": msg}) return ret
def copy(self): return Conversation( name=self.name, system_template=self.system_template, system_message=self.system_message, roles=self.roles, messages=[[x, y] for x, y in self.messages], offset=self.offset, sep_style=self.sep_style, sep=self.sep, sep2=self.sep2, stop_str=self.stop_str, stop_token_ids=self.stop_token_ids, )
def dict(self): return { "template_name": self.name, "system_message": self.system_message, "roles": self.roles, "messages": self.messages, "offset": self.offset, }
# A global registry for all conversation templatesconv_templates: Dict[str, Conversation] = {}
def register_conv_template(template: Conversation, override: bool = False): """Register a new conversation template.""" if not override: assert template.name not in conv_templates, f"{template.name} has been registered."
conv_templates[template.name] = template
def get_conv_template(name: str) -> Conversation: """Get a conversation template.""" return conv_templates[name].copy()
register_conv_template( Conversation( name="deepseek", system_template="{system_message}", # system_message="You are a helpful assistant. Please answer truthfully and write out your " # "thinking step by step to be sure you get the right answer.", system_message="", roles=("<|User|>", "<|Assistant|>"), messages=(), offset=0, sep_style=SeparatorStyle.DeepSeek, sep="\n\n", sep2="<|end▁of▁sentence|>", stop_token_ids=[100001], stop_str=["User:", "<|end▁of▁sentence|>"] ))register_conv_template( Conversation( name="deepseekv2", system_template="{system_message}", # system_message="You are a helpful assistant. Please answer truthfully and write out your " # "thinking step by step to be sure you get the right answer.", system_message="", roles=("<|User|>", "<|Assistant|>"), messages=(), offset=0, sep_style=SeparatorStyle.DeepSeek, sep="", sep2="<|end▁of▁sentence|>", stop_token_ids=[100001], stop_str=["User:", "<|end▁of▁sentence|>"] ))
register_conv_template( Conversation( name="plain", system_template="", system_message="", roles=("", ""), messages=(), offset=0, sep_style=SeparatorStyle.PLAIN, sep="", sep2="", stop_token_ids=[100001], stop_str=['</s>'], ))
register_conv_template( Conversation( name="alignment", system_template="", system_message="", roles=("", ""), messages=(), offset=0, sep_style=SeparatorStyle.ALIGNMENT, sep="", sep2="", stop_token_ids=[100001], stop_str=['</s>'], ))
if __name__ == "__main__": print("deepseek template:") conv = get_conv_template("deepseek") conv.append_message(conv.roles[0], "Hello!") conv.append_message(conv.roles[1], "Hi! This is Tony.") conv.append_message(conv.roles[0], "Who are you?") conv.append_message(conv.roles[1], "I am a helpful assistant.") conv.append_message(conv.roles[0], "How are you?") conv.append_message(conv.roles[1], None) print(conv.get_prompt())
print("deepseekv2 template:") conv = get_conv_template("deepseekv2") conv.append_message(conv.roles[0], "Hello!") conv.append_message(conv.roles[1], "Hi! This is Tony.") conv.append_message(conv.roles[0], "Who are you?") conv.append_message(conv.roles[1], "I am a helpful assistant.") conv.append_message(conv.roles[0], "How are you?") conv.append_message(conv.roles[1], None) print(conv.get_prompt())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956import torch.nn as nnimport torchimport torch.nn.functional as Fimport copyimport osimport math
from typing import Optional, Tuple
# from megatron.model import LayerNorm
import transformers
from typing import Optional, Tuple, Typefrom functools import partialimport math
def scanflow_debug_tensor(name, x): if x is None: print(f"[scanflow debug] {name}: None", flush=True) return
try: t = x.detach() finite = torch.isfinite(t) if torch.is_floating_point(t) else torch.ones_like(t, dtype=torch.bool) finite_count = int(finite.sum().item()) total = t.numel()
msg = ( f"[scanflow debug] {name}: " f"shape={tuple(t.shape)} dtype={t.dtype} device={t.device} " f"finite={finite_count}/{total}" )
if torch.is_floating_point(t) and finite_count > 0: tf = t[finite] msg += ( f" min={tf.min().item():.6g}" f" max={tf.max().item():.6g}" f" mean={tf.float().mean().item():.6g}" )
print(msg, flush=True) except Exception as exc: print(f"[scanflow debug] {name}: failed to summarize: {exc}", flush=True)
def scanflow_is_main_process() -> bool: return not ( torch.distributed.is_available() and torch.distributed.is_initialized() and torch.distributed.get_rank() != 0 )
def scanflow_log_interval() -> int: return max(1, int(os.getenv("SCANFLOW_DIAGNOSTIC_LOG_INTERVAL", "10")))
def scanflow_env_flag(name: str, default: str = "0") -> bool: return os.getenv(name, default).strip().lower() in {"1", "true", "yes", "on"}
def scanflow_env_float(name: str, default: str = "0.0") -> float: try: return float(os.getenv(name, default)) except (TypeError, ValueError): return float(default)
def scanflow_log_attention_outputs( *, forward_step: int, visual_attn_maps: Optional[torch.Tensor],) -> None: """Log ScanFlow visual-attention maps used for attention-level fixation supervision.""" if not scanflow_is_main_process(): return if os.getenv("SCANFLOW_LOG_ATTENTION_OUTPUTS", "1") != "1": return if forward_step % scanflow_log_interval() != 0: return if visual_attn_maps is None: print( f"[scanflow attention outputs] forward_step={forward_step} maps=None", flush=True, ) return
with torch.no_grad(): maps = visual_attn_maps.detach().float() row_sums = maps.sum(dim=-1) entropy = -(maps.clamp_min(1e-12) * maps.clamp_min(1e-12).log()).sum(dim=-1) max_probs = maps.max(dim=-1).values print( "[scanflow attention outputs] " f"forward_step={forward_step} " f"shape={tuple(maps.shape)} " f"mean={maps.mean().item():.8g} " f"std={maps.std().item():.8g} " f"min={maps.min().item():.8g} " f"max={maps.max().item():.8g} " f"row_sum_mean={row_sums.mean().item():.8g} " f"row_sum_min={row_sums.min().item():.8g} " f"row_sum_max={row_sums.max().item():.8g} " f"entropy_mean={entropy.mean().item():.8g} " f"max_prob_mean={max_probs.mean().item():.8g} " f"finite={bool(torch.isfinite(maps).all().item())}", flush=True, )
def scanflow_log_fixation_outputs( *, forward_step: int, fixation_logits: Optional[torch.Tensor], scanpath_hidden: Optional[torch.Tensor], visual_tokens: Optional[torch.Tensor], logit_scale: Optional[torch.Tensor],) -> None: """Log whether the fixation decoder is escaping the uniform solution.""" if not scanflow_is_main_process(): return if os.getenv("SCANFLOW_LOG_FIXATION_OUTPUTS", "1") != "1": return if forward_step % scanflow_log_interval() != 0: return if fixation_logits is None: print( f"[scanflow fixation outputs] forward_step={forward_step} logits=None", flush=True, ) return
with torch.no_grad(): logits = fixation_logits.detach().float() log_probs = F.log_softmax(logits, dim=-1) probs = log_probs.exp() entropy = -(probs * log_probs).sum(dim=-1) max_probs, argmax = probs.max(dim=-1)
message = ( "[scanflow fixation outputs] " f"forward_step={forward_step} " f"shape={tuple(logits.shape)} " f"logit_mean={logits.mean().item():.8g} " f"logit_std={logits.std().item():.8g} " f"logit_min={logits.min().item():.8g} " f"logit_max={logits.max().item():.8g} " f"logit_range={(logits.max() - logits.min()).item():.8g} " f"prob_max_mean={max_probs.mean().item():.8g} " f"prob_max_min={max_probs.min().item():.8g} " f"prob_max_max={max_probs.max().item():.8g} " f"prediction_entropy={entropy.mean().item():.8g} " f"first_argmax={int(argmax.reshape(-1)[0].item())} " f"finite={bool(torch.isfinite(logits).all().item())}" )
if scanpath_hidden is not None: hidden = scanpath_hidden.detach().float() message += ( f" hidden_mean={hidden.mean().item():.8g}" f" hidden_std={hidden.std().item():.8g}" f" hidden_norm={hidden.norm().item():.8g}" f" hidden_finite={bool(torch.isfinite(hidden).all().item())}" )
if visual_tokens is not None: visual = visual_tokens.detach().float() message += ( f" visual_mean={visual.mean().item():.8g}" f" visual_std={visual.std().item():.8g}" f" visual_norm={visual.norm().item():.8g}" )
if logit_scale is not None: scale = logit_scale.detach().float() message += ( f" logit_scale={scale.mean().item():.8g}" f" logit_scale_abs={scale.abs().mean().item():.8g}" )
print(message, flush=True)
class MlpProjector(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
if cfg.projector_type == "identity": modules = nn.Identity()
elif cfg.projector_type == "linear": modules = nn.Linear(cfg.input_dim, cfg.n_embed)
elif cfg.projector_type == "mlp_gelu": mlp_depth = cfg.get("depth", 1) modules = [nn.Linear(cfg.input_dim, cfg.n_embed)] for _ in range(1, mlp_depth): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed, cfg.n_embed)) modules = nn.Sequential(*modules) elif cfg.projector_type == "normlayer_downsample_mlp_gelu": mlp_depth = cfg.get("depth", 1) mlp_ratio = cfg.get("mlp_ratio", 1) modules = [ nn.LayerNorm(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio), nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio) ] for _ in range(1, mlp_depth - 1): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio)) modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed)) modules = nn.Sequential(*modules) elif cfg.projector_type == "downsample_mlp_gelu": mlp_depth = cfg.get("depth", 1) mlp_ratio = cfg.get("mlp_ratio", 1) modules = [nn.Linear(cfg.input_dim * cfg.downsample_ratio * cfg.downsample_ratio, cfg.n_embed * mlp_ratio)] for _ in range(1, mlp_depth - 1): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed * mlp_ratio)) modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed * mlp_ratio, cfg.n_embed)) modules = nn.Sequential(*modules)
elif cfg.projector_type == "low_high_hybrid_split_mlp_gelu": mlp_depth = cfg.get("depth", 1) self.high_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2) self.low_up_proj = nn.Linear(cfg.input_dim, cfg.n_embed // 2)
modules = [] for _ in range(1, mlp_depth): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed, cfg.n_embed)) modules = nn.Sequential(*modules)
elif cfg.projector_type == "hybrid_split_feature_mlp_gelu": mlp_depth = cfg.get("depth", 1) channel_div = cfg.get("channel_div", 0.5) self.high_up_proj = nn.Linear(cfg.input_dim[0], int(cfg.n_embed * channel_div)) self.low_up_proj = nn.Linear(cfg.input_dim[1], cfg.n_embed - int(cfg.n_embed * channel_div))
modules = [] for _ in range(1, mlp_depth): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed, cfg.n_embed)) modules = nn.Sequential(*modules)
elif cfg.projector_type == "low_high_split_mlp_gelu": mlp_depth = cfg.get("depth", 1) modules = [] for _ in range(1, mlp_depth): modules.append(nn.GELU()) modules.append(nn.Linear(cfg.n_embed // 2, cfg.n_embed // 2)) modules = nn.Sequential(*modules) self.high_layers = nn.Sequential(*modules) self.low_layers = copy.deepcopy(modules)
else: raise ValueError(f"Unknown projector type: {cfg.projector_type}")
if cfg.get("token_pooling", False): self.token_pooling_layer = nn.Linear(cfg.input_dim * 4, cfg.input_dim)
if cfg.get("conv_fusion_high_low_features", False): self.fusion_layer = nn.Linear(cfg.input_dim, cfg.input_dim) self.layers = modules
def forward(self, x): if self.cfg.get("token_pooling", False): batch_size, wxh, channels = x.shape w = h = int(wxh**0.5) x = x.view(batch_size, w, h, channels) x = x.permute(0, 3, 1, 2) # import ipdb; ipdb.set_trace() patches = x.unfold(2, 2, 2).unfold(3, 2, 2) batch_size, channels, h_patches, w_patches, _, _ = patches.size() # 在通道维度上拼接 patches = patches.contiguous().view(batch_size, channels, h_patches * w_patches, -1)
# 通过线性层 patches = patches.permute(0, 2, 1, 3).contiguous() patches = patches.view(batch_size, h_patches * w_patches, channels * 4)
x = self.token_pooling_layer(patches) if self.cfg.get("conv_fusion_high_low_features", False): x = self.fusion_layer(x[:, 0]) + x[:, 1]
if self.cfg.projector_type == 'low_high_hybrid_split_mlp_gelu': high_x, low_x = x[0], x[1] high_x = self.high_up_proj(high_x) low_x = self.low_up_proj(low_x) x = torch.concat([high_x, low_x], dim=-1) if self.cfg.projector_type == 'hybrid_split_feature_mlp_gelu': high_x = x[...,:self.cfg.input_dim[0]] low_x = x[...,self.cfg.input_dim[0]:] high_x = self.high_up_proj(high_x) low_x = self.low_up_proj(low_x) x = torch.concat([high_x, low_x], dim=-1) if self.cfg.projector_type == 'low_high_split_mlp_gelu': high_x, low_x = x[0], x[1] high_x = self.high_layers(high_x) low_x = self.low_layers(low_x) x = torch.concat([high_x, low_x], dim=-1) return x if self.cfg.projector_type == 'downsample_mlp_gelu' or self.cfg.projector_type == 'normlayer_downsample_mlp_gelu': bs, hw, input_dim = x.shape h = w = int((hw) ** 0.5)
"""compute padding""" if h % self.cfg.downsample_ratio: pad = self.cfg.downsample_ratio - h % self.cfg.downsample_ratio else: pad = 0 x = x.reshape(bs, h, w, input_dim) if pad > 0: x = F.pad(x, (0, 0, 0, pad, 0, pad), "constant", 0)
"""4 to 1 concat""" x = x.permute(0, 3, 1, 2) # B, C, H, W x = F.unfold(x, kernel_size=self.cfg.downsample_ratio, stride=self.cfg.downsample_ratio, padding=0) # B, C*4, HW // 4 x = x.permute(0, 2, 1) return self.layers(x)
@staticmethod def get_flops_per_sample(cfg): if cfg.projector_type == "linear": fwd = 2 * cfg.input_dim * cfg.n_embed
elif "mlp_gelu" in cfg.projector_type : mlp_depth = cfg.get("depth", 1) downsample_ratio = cfg.get("downsample_ratio", 1) input_dim = sum(cfg.input_dim) if isinstance(cfg.input_dim, list) else cfg.input_dim input_dim = input_dim * downsample_ratio * downsample_ratio fwd = 2 * input_dim * cfg.n_embed + (mlp_depth - 1) * 2 * cfg.n_embed * cfg.n_embed else: fwd = 0
return fwd * 3
#===================qwen2================================
class CustomQwen2Decoder(nn.Module): """Qwen2 visual/reasoning encoder used by recurrent Plan 1.
token_type_ids: 0 = bidirectional visual token 1 = causal recurrent reasoning token
After every pretrained Qwen decoder layer, question information is injected through a separate cross-attention residual on causal positions only. Visual positions are left unchanged by the text cross-attention branch.
Gradient-checkpointing note --------------------------- The text cross-attention is executed *inside the checkpointed layer function*. text_context and token_type_ids are explicit checkpoint inputs, so backward recomputation follows exactly the same graph as the original forward. This intentionally avoids forward hooks and mutable outer-module "active context" state, which are not safe under activation checkpoint recomputation. """
def __init__( self, decoder_layer: int = 24, max_position_embeddings: int = 131072, hidden_dimension: int = 896, num_attention_heads: int = 14, num_key_value_heads: int = 2, intermediate_size: int = 4864, vocab_size: int = 151936, attn_implementation: str = "sdpa", rms_norm_eps: float = 1e-06, rope_theta: float = 1000000.0, attention_dropout: float = 0.0, hidden_act: str = "silu", initializer_range: float = 0.02, enable_text_cross_attention: bool = True, ): super().__init__() self.enable_text_cross_attention = bool(enable_text_cross_attention) self.hidden_dimension = hidden_dimension
if attn_implementation == "flash_attention_2": raise ValueError( "CustomQwen2Decoder does not support flash_attention_2; " "the asymmetric visual/causal mask requires sdpa or eager." )
Qwen2Model = getattr(transformers.models.qwen2.modeling_qwen2, "Qwen2Model") Qwen2Config = getattr(transformers, "Qwen2Config") config = Qwen2Config( hidden_size=hidden_dimension, num_hidden_layers=decoder_layer, num_attention_heads=num_attention_heads, num_key_value_heads=num_key_value_heads, intermediate_size=intermediate_size, max_position_embeddings=max_position_embeddings, vocab_size=vocab_size, rms_norm_eps=rms_norm_eps, rope_theta=rope_theta, attention_dropout=attention_dropout, hidden_act=hidden_act, initializer_range=initializer_range, _attn_implementation=attn_implementation, )
# Preserve the original pretrained Qwen module/state-dict hierarchy. self.model = self._create_custom_model(Qwen2Model, config)
# Keep the exact parameter/state-dict names used by the previous recurrent # Plan-1 implementation. Only the execution mechanism changes: these # modules are now called explicitly inside the checkpointed layer unit. self.text_cross_norms = nn.ModuleList([ nn.LayerNorm(hidden_dimension) for _ in range(decoder_layer) ]) self.text_cross_attn_layers = nn.ModuleList([ nn.MultiheadAttention( hidden_dimension, num_attention_heads, dropout=attention_dropout, batch_first=True, ) for _ in range(decoder_layer) ])
# inputs_embeds are always supplied by ScanFlow, so the unused embedding # table is removed exactly as before. del self.model.embed_tokens
def _apply_text_cross_attention( self, layer_idx: int, hidden_states: torch.Tensor, text_context: Optional[torch.Tensor], token_type_ids: torch.Tensor, ) -> torch.Tensor: """Apply the existing causal-only text residual after one Qwen layer.""" if not self.enable_text_cross_attention or text_context is None: return hidden_states
causal_mask = token_type_ids.eq(1) if causal_mask.shape != hidden_states.shape[:2]: raise ValueError( "token_type_ids must match hidden_states[:2], got " f"{tuple(causal_mask.shape)} vs {tuple(hidden_states.shape[:2])}." )
causal_counts = causal_mask.sum(dim=1) if int(causal_counts.max().item()) == 0: return hidden_states if not torch.equal(causal_counts, causal_counts[:1].expand_as(causal_counts)): raise ValueError( "Recurrent Plan 1 requires the same active causal sequence length " "within a single Qwen call." )
batch_size = hidden_states.size(0) num_causal = int(causal_counts[0].item())
# This is intentionally identical to the former forward-hook branch: # normalize the complete layer output, query only causal positions, then # add the text-attention residual only at those causal positions. normed = self.text_cross_norms[layer_idx](hidden_states) causal_query = normed[causal_mask].view( batch_size, num_causal, hidden_states.size(-1) ) text_context_local = text_context.to( device=hidden_states.device, dtype=hidden_states.dtype, ) text_residual, _ = self.text_cross_attn_layers[layer_idx]( causal_query, text_context_local, text_context_local, need_weights=False, )
updated = hidden_states.clone() updated[causal_mask] = ( hidden_states[causal_mask] + text_residual.reshape(-1, hidden_states.size(-1)) ) return updated
def _run_qwen_layer_with_text( self, *, layer_idx: int, decoder_layer: nn.Module, hidden_states: torch.Tensor, causal_mask: torch.Tensor, position_ids: torch.Tensor, past_key_values, output_attentions: bool, use_cache: bool, cache_position: torch.Tensor, position_embeddings, text_context: Optional[torch.Tensor], token_type_ids: torch.Tensor, ): """One architecture-faithful unit: Qwen layer -> text cross-attention.""" layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, )
updated_hidden = self._apply_text_cross_attention( layer_idx=layer_idx, hidden_states=layer_outputs[0], text_context=text_context, token_type_ids=token_type_ids, ) return (updated_hidden, *layer_outputs[1:])
def _create_custom_model(self, Qwen2Model, config): class CustomQwen2ModelInner(Qwen2Model): """Qwen2Model retaining only ScanFlow's asymmetric-mask helper.
No recurrent-step state is stored on this module. In particular, token_type_ids are passed explicitly by CustomQwen2Decoder.forward. """
def build_scanflow_causal_mask( self, attention_mask, input_tensor, token_type_ids, ): dtype, device = input_tensor.dtype, input_tensor.device min_dtype = torch.finfo(dtype).min batch_size, sequence_length = input_tensor.shape[:2]
if token_type_ids is None: raise ValueError( "Recurrent Plan 1 requires token_type_ids for its asymmetric " "visual/causal attention mask." ) if token_type_ids.shape != (batch_size, sequence_length): raise ValueError( "token_type_ids must have shape [B,S] matching inputs_embeds, got " f"{tuple(token_type_ids.shape)} vs {(batch_size, sequence_length)}." )
causal_mask = self._create_custom_4d_mask( sequence_length=sequence_length, dtype=dtype, device=device, batch_size=batch_size, token_type_ids=token_type_ids, ) if attention_mask is not None: if attention_mask.dim() != 2: raise ValueError( "Recurrent Plan 1 expects an optional 2D attention_mask, got " f"shape={tuple(attention_mask.shape)}." ) padding_mask = attention_mask[:, None, None, :].to(dtype=dtype) padding_mask = (1.0 - padding_mask) * min_dtype causal_mask = causal_mask + padding_mask return causal_mask
def _create_custom_4d_mask( self, sequence_length, dtype, device, batch_size, token_type_ids, ): min_dtype = torch.finfo(dtype).min masks = [] for b in range(batch_size): mask = torch.full( (sequence_length, sequence_length), fill_value=min_dtype, dtype=dtype, device=device, ) type_ids = token_type_ids[b] visual_positions = (type_ids == 0).nonzero(as_tuple=True)[0] causal_positions = (type_ids == 1).nonzero(as_tuple=True)[0]
# Visual tokens remain a bidirectional visual context. if len(visual_positions) > 0: mask[visual_positions[:, None], visual_positions] = 0.0
# Recurrent reasoning tokens see all visual tokens and only # themselves / earlier causal reasoning states. for i, causal_pos in enumerate(causal_positions): if len(visual_positions) > 0: mask[causal_pos, visual_positions] = 0.0 mask[causal_pos, causal_positions[: i + 1]] = 0.0
masks.append(mask) return torch.stack(masks, dim=0).unsqueeze(1)
return CustomQwen2ModelInner(config)
def forward( self, inputs_embeds, token_type_ids, attention_mask=None, text_context: Optional[torch.Tensor] = None, **kwargs, ): """Run Qwen with checkpoint-safe per-layer text injection.
This mirrors the layer loop of transformers==4.46.3 Qwen2Model.forward, but replaces the checkpoint target from a bare Qwen decoder layer with the architecture-faithful composite operation:
QwenDecoderLayer -> causal-only text cross-attention residual
Crucially, text_context and token_type_ids are explicit inputs to the checkpointed function. They are therefore available unchanged during backward recomputation. """ from transformers.modeling_outputs import BaseModelOutputWithPast
output_attentions = kwargs.pop("output_attentions", None) output_hidden_states = kwargs.pop("output_hidden_states", None) return_dict = kwargs.pop("return_dict", None) use_cache = kwargs.pop("use_cache", None) position_ids = kwargs.pop("position_ids", None) cache_position = kwargs.pop("cache_position", None) past_key_values = kwargs.pop("past_key_values", None)
if kwargs: raise TypeError( "Unexpected CustomQwen2Decoder.forward keyword arguments: " f"{sorted(kwargs.keys())}" )
output_attentions = ( output_attentions if output_attentions is not None else self.model.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.model.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.model.config.use_return_dict ) use_cache = use_cache if use_cache is not None else self.model.config.use_cache
# Recurrent Plan 1 always calls this encoder with use_cache=False. Keeping # this explicit also avoids silently constructing a cache whose key length # would not match the custom asymmetric [S,S] mask. if use_cache or past_key_values is not None: raise ValueError( "Recurrent Plan-1 CustomQwen2Decoder does not use KV caching. " "Call it with use_cache=False and past_key_values=None." )
if inputs_embeds is None: raise ValueError("inputs_embeds must be provided for recurrent Plan 1.") if token_type_ids is None: raise ValueError("token_type_ids must be provided for recurrent Plan 1.")
batch_size, sequence_length = inputs_embeds.shape[:2] if token_type_ids.shape != (batch_size, sequence_length): raise ValueError( "token_type_ids must match inputs_embeds[:2], got " f"{tuple(token_type_ids.shape)} vs {(batch_size, sequence_length)}." )
if cache_position is None: cache_position = torch.arange( 0, sequence_length, device=inputs_embeds.device, ) if position_ids is None: position_ids = cache_position.unsqueeze(0)
causal_mask = self.model.build_scanflow_causal_mask( attention_mask=attention_mask, input_tensor=inputs_embeds, token_type_ids=token_type_ids, )
hidden_states = inputs_embeds position_embeddings = self.model.rotary_emb(hidden_states, position_ids)
all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None
gradient_checkpointing = bool( getattr(self.model, "gradient_checkpointing", False) and self.training ) capture_layer_indices = getattr( self, "scanflow_attention_layer_indices", None, )
for layer_idx, decoder_layer in enumerate(self.model.layers): layer_output_attentions = bool(output_attentions) and ( capture_layer_indices is None or layer_idx in capture_layer_indices ) if output_hidden_states: all_hidden_states += (hidden_states,)
if gradient_checkpointing: # Do NOT checkpoint decoder_layer.__call__ alone. The text branch # is part of the layer-level computation and must be recomputed # together with it. The tensors that vary by recurrent step are # explicit checkpoint inputs rather than mutable module state. def checkpointed_layer( layer_hidden_states, layer_causal_mask, layer_position_ids, layer_cache_position, layer_position_embeddings, layer_text_context, layer_token_type_ids, *, _layer_idx=layer_idx, _decoder_layer=decoder_layer, _output_attentions=layer_output_attentions, ): return self._run_qwen_layer_with_text( layer_idx=_layer_idx, decoder_layer=_decoder_layer, hidden_states=layer_hidden_states, causal_mask=layer_causal_mask, position_ids=layer_position_ids, past_key_values=None, output_attentions=_output_attentions, use_cache=False, cache_position=layer_cache_position, position_embeddings=layer_position_embeddings, text_context=layer_text_context, token_type_ids=layer_token_type_ids, )
# text_context can legitimately be None, but recurrent Plan 1 # normally provides it. For the no-text case use an empty tensor # as an explicit checkpoint input and map it back to None inside # the closure so PyTorch receives only stable positional args. if text_context is None: checkpoint_text_context = hidden_states.new_empty( batch_size, 0, self.hidden_dimension ) text_context_is_none = True else: checkpoint_text_context = text_context text_context_is_none = False
if text_context_is_none: def checkpointed_layer_no_text( layer_hidden_states, layer_causal_mask, layer_position_ids, layer_cache_position, layer_position_embeddings, _checkpoint_text_context, layer_token_type_ids, *, _layer_idx=layer_idx, _decoder_layer=decoder_layer, _output_attentions=layer_output_attentions, ): return self._run_qwen_layer_with_text( layer_idx=_layer_idx, decoder_layer=_decoder_layer, hidden_states=layer_hidden_states, causal_mask=layer_causal_mask, position_ids=layer_position_ids, past_key_values=None, output_attentions=_output_attentions, use_cache=False, cache_position=layer_cache_position, position_embeddings=layer_position_embeddings, text_context=None, token_type_ids=layer_token_type_ids, ) checkpoint_fn = checkpointed_layer_no_text else: checkpoint_fn = checkpointed_layer
layer_outputs = self.model._gradient_checkpointing_func( checkpoint_fn, hidden_states, causal_mask, position_ids, cache_position, position_embeddings, checkpoint_text_context, token_type_ids, ) else: layer_outputs = self._run_qwen_layer_with_text( layer_idx=layer_idx, decoder_layer=decoder_layer, hidden_states=hidden_states, causal_mask=causal_mask, position_ids=position_ids, past_key_values=None, output_attentions=layer_output_attentions, use_cache=False, cache_position=cache_position, position_embeddings=position_embeddings, text_context=text_context, token_type_ids=token_type_ids, )
hidden_states = layer_outputs[0] if output_attentions: # Preserve layer indexing while retaining attention tensors only # for the four recurrent Plan-1 supervision layers. all_self_attns += ( layer_outputs[1] if layer_output_attentions else None, )
hidden_states = self.model.norm(hidden_states)
if output_hidden_states: all_hidden_states += (hidden_states,)
if not return_dict: return tuple( value for value in [hidden_states, None, all_hidden_states, all_self_attns] if value is not None )
return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=None, hidden_states=all_hidden_states, attentions=all_self_attns, )
# batch_size = 2# inputs_embeds = torch.randn(batch_size, 512, 896).cuda()
# inputs_embeds = torch.randn(batch_size, 512, 896).cuda()# token_type_ids = torch.cat([# torch.zeros(batch_size, 256, dtype=torch.long),# torch.ones(batch_size, 256, dtype=torch.long),# ], dim=1).cuda()
# # start = time.time()# with torch.no_grad():# outputs_sdpa = decoder_sdpa(inputs_embeds, token_type_ids)# print(outputs_sdpa[0].shape)# print(f"SDPA time: {time.time() - start:.4f}s")
class Qwen2Decoder2Encoder(nn.Module): """ScanFlow Pro V2 dynamic spatial/intensity residual baseline.
The checkpoint-compatible Plan-1 recurrent path that generates h_t is kept intact:
h_0 = mean(V) h_t = Qwen(V, h_1, ..., h_{t-1}, seed_t)[-1] seed_1 = h_0 seed_t = h_{t-1} (t > 1)
V2 does not change visual perception inside the recurrent loop. Only after the complete temporal reasoning sequence H=[h_1,...,h_T] has been generated, the immutable visual tokens query H once to obtain a global reasoning residual:
R_i = CrossAttention(query=V, key=H, value=H)_i lambda_i = sigmoid(F_I([v_i, pool(V), pool(Q)])) V_v2_i = V_i + lambda_i * R_i
The returned sequence is [V_v2; H]. This intentionally has no stepwise perceptual update, fixation-controlled write, or feedback from R/lambda into later h_t states. Its tokenwise intensity is dynamic across samples and questions, giving V2 spatial and reasoning-intensity axes while retaining no temporal perception-update axis. """
def __init__( self, decoder_layer: int, hidden_dimension: int, num_attention_heads: int, num_key_value_heads: int, intermediate_size: int, max_query: int, text_hidden_dim: int = 1280, max_scanpath_steps: int = 32, scanpath_layers: int = 2, # retained only for checkpoint/config compatibility scanpath_dropout: float = 0.0, # retained only for checkpoint/config compatibility ): super().__init__() del max_query, scanpath_layers, scanpath_dropout self.hidden_dimension = hidden_dimension self.text_hidden_dim = text_hidden_dim self.max_scanpath_steps = max_scanpath_steps
self.enable_attention_supervision = ( scanflow_env_flag("DEEPSEEK_OCR2_ENABLE_ATTENTION_SUPERVISION", "0") or scanflow_env_float("DEEPSEEK_OCR2_ATTENTION_LOSS_WEIGHT", "0.0") != 0.0 )
# Recurrent Plan-1 attention supervision: # supervise the four central Qwen layers. For a 24-layer encoder these # are 0-based layers [10, 11, 12, 13]. An explicit comma-separated # override is still available for controlled ablations. raw_attention_layers = os.getenv( "DEEPSEEK_OCR2_ATTENTION_LAYER_INDICES", "" ).strip() if raw_attention_layers: attention_layer_indices = [ int(item.strip()) for item in raw_attention_layers.split(",") if item.strip() ] else: if decoder_layer < 4: raise ValueError( "Middle-four attention supervision requires at least 4 Qwen layers, " f"got decoder_layer={decoder_layer}." ) middle_start = (decoder_layer - 4) // 2 attention_layer_indices = list(range(middle_start, middle_start + 4))
if len(attention_layer_indices) != 4: raise ValueError( "DEEPSEEK_OCR2_ATTENTION_LAYER_INDICES must contain exactly four " f"layer indices, got {attention_layer_indices}." ) if len(set(attention_layer_indices)) != 4: raise ValueError( "Attention supervision layer indices must be unique, got " f"{attention_layer_indices}." ) for layer_idx in attention_layer_indices: if layer_idx < 0 or layer_idx >= decoder_layer: raise ValueError( f"Attention supervision layer index {layer_idx} is out of range " f"for decoder_layer={decoder_layer}." )
self.attention_supervision_layer_indices = tuple(attention_layer_indices)
# Keep eager attention for exact compatibility with the trained recurrent # Plan-1 attention path and its middle-four-layer supervision. qwen_attn_implementation = "eager" self.model = CustomQwen2Decoder( decoder_layer=decoder_layer, hidden_dimension=hidden_dimension, num_attention_heads=num_attention_heads, num_key_value_heads=num_key_value_heads, intermediate_size=intermediate_size, attn_implementation=qwen_attn_implementation, enable_text_cross_attention=True, ) self.model.scanflow_attention_layer_indices = ( self.attention_supervision_layer_indices ) self.text_context_proj = nn.Linear(text_hidden_dim, hidden_dimension)
# Version-2 global residual branch. It is registered under ``self.model`` # so the existing MS-Swift trainable prefix # ``model.qwen2_model.model`` includes it without changing the selection # used by recurrent Plan-1 checkpoints. self.model.scanflow_v2_visual_norm = nn.LayerNorm(hidden_dimension) self.model.scanflow_v2_reasoning_norm = nn.LayerNorm(hidden_dimension) self.model.scanflow_v2_residual_attn = nn.MultiheadAttention( hidden_dimension, num_attention_heads, dropout=0.0, batch_first=True, ) # Tokenwise reasoning intensity lambda_i(V,Q). Local V_i supplies the # spatial axis, while pooled V and pooled question tokens supply global # image/question context. Register under ``self.model`` so the existing # MS-Swift trainable prefix includes every newly introduced parameter. self.model.scanflow_v2_intensity_visual_norm = nn.LayerNorm( hidden_dimension ) self.model.scanflow_v2_intensity_question_norm = nn.LayerNorm( hidden_dimension ) self.model.scanflow_v2_intensity_mlp = nn.Sequential( nn.Linear(3 * hidden_dimension, hidden_dimension), nn.SiLU(), nn.Linear(hidden_dimension, 1), ) self.scanflow_v2_initial_intensity = scanflow_env_float( "SCANFLOW_V2_INITIAL_INTENSITY", "0.001" ) if not 0.0 < self.scanflow_v2_initial_intensity < 1.0: raise ValueError( "SCANFLOW_V2_INITIAL_INTENSITY must be strictly between 0 and 1, " f"got {self.scanflow_v2_initial_intensity}." ) self._reset_scanflow_v2_residual_branch()
# Compatibility aliases for outer code. They no longer indicate an # external ScanFlow module; recurrence is intrinsic to this encoder. self.enable_scanflow = True self.enable_text_query_residual = True
self.last_scanpath_hidden = None self.last_reasoning_residual = None self.last_reasoning_intensity = None self.last_residual_visual_tokens = None self.last_scanflow_output = None self.last_visual_attn_maps = None self.last_visual_attn_layer_indices = self.attention_supervision_layer_indices self.last_scanpath_mask = None self._scanflow_diagnostic_forward_step = 0
def _reset_scanflow_v2_residual_branch(self): """Reset only the new R=CrossAttn(V,H,H) and lambda_i(V,Q) branch.""" visual_norm = self.model.scanflow_v2_visual_norm reasoning_norm = self.model.scanflow_v2_reasoning_norm residual_attn = self.model.scanflow_v2_residual_attn intensity_visual_norm = self.model.scanflow_v2_intensity_visual_norm intensity_question_norm = self.model.scanflow_v2_intensity_question_norm intensity_mlp = self.model.scanflow_v2_intensity_mlp
with torch.no_grad(): nn.init.ones_(visual_norm.weight) nn.init.zeros_(visual_norm.bias) nn.init.ones_(reasoning_norm.weight) nn.init.zeros_(reasoning_norm.bias) nn.init.xavier_uniform_(residual_attn.in_proj_weight) if residual_attn.in_proj_bias is not None: nn.init.zeros_(residual_attn.in_proj_bias) nn.init.xavier_uniform_(residual_attn.out_proj.weight) if residual_attn.out_proj.bias is not None: nn.init.zeros_(residual_attn.out_proj.bias) nn.init.ones_(intensity_visual_norm.weight) nn.init.zeros_(intensity_visual_norm.bias) nn.init.ones_(intensity_question_norm.weight) nn.init.zeros_(intensity_question_norm.bias) nn.init.xavier_uniform_(intensity_mlp[0].weight) nn.init.zeros_(intensity_mlp[0].bias)
# A zero output weight makes every token's initial gate exactly the # requested checkpoint-safe value. The output layer learns on the # first optimizer step; gradients reach the first layer once that # output weight becomes nonzero. nn.init.zeros_(intensity_mlp[2].weight) initial_logit = math.log( self.scanflow_v2_initial_intensity / (1.0 - self.scanflow_v2_initial_intensity) ) nn.init.constant_(intensity_mlp[2].bias, initial_logit)
def reset_scanflow_parameters(self): """Reset only the NEW recurrent-Plan-1 text-injection parameters.
This is the original Plan-1 reset path and is intentionally kept independent from the ScanFlow Pro V2 reset path. """ def _reset_module(module): for m in module.modules(): if isinstance(m, nn.MultiheadAttention): nn.init.xavier_uniform_(m.in_proj_weight) if m.in_proj_bias is not None: nn.init.zeros_(m.in_proj_bias) elif isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.LayerNorm): if m.weight is not None: nn.init.ones_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias)
_reset_module(self.model.text_cross_norms) _reset_module(self.model.text_cross_attn_layers) nn.init.xavier_uniform_(self.text_context_proj.weight) if self.text_context_proj.bias is not None: nn.init.zeros_(self.text_context_proj.bias)
if scanflow_is_main_process(): print( "[scanflow reset] recurrent Plan-1 new parameters reinitialized: " "text_cross_norms, text_cross_attn_layers, text_context_proj; " "pretrained Qwen weights preserved.", flush=True, )
def reset_scanflow_v2_parameters(self): """Reset only modules newly introduced by ScanFlow Pro V2.""" self._reset_scanflow_v2_residual_branch()
if scanflow_is_main_process(): print( "[scanflow v2 reset] global reasoning-residual cross-attention " "and dynamic lambda_i(V,Q) head reinitialized with " f"lambda_i={self.scanflow_v2_initial_intensity:g}; all recurrent Plan-1 " "checkpoint parameters preserved.", flush=True, )
def _compute_global_reasoning_residual( self, visual_tokens: torch.Tensor, scanpath_hidden: torch.Tensor, scanpath_padding_mask: Optional[torch.Tensor], question_tokens: Optional[torch.Tensor], ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Return R, lambda_i(V,Q), and V+lambda_i*R after recurrence.
The cross-attention is intentionally evaluated once, outside the recurrence. Consequently R cannot affect the production of H and this baseline contains no stepwise perceptual feedback. """ query = self.model.scanflow_v2_visual_norm(visual_tokens) reasoning = self.model.scanflow_v2_reasoning_norm(scanpath_hidden) residual, _ = self.model.scanflow_v2_residual_attn( query=query, key=reasoning, value=reasoning, key_padding_mask=scanpath_padding_mask, need_weights=False, ) residual = residual.to(dtype=visual_tokens.dtype)
intensity_visual = self.model.scanflow_v2_intensity_visual_norm( visual_tokens ) pooled_visual = intensity_visual.mean(dim=1, keepdim=True).expand( -1, visual_tokens.size(1), -1 ) if question_tokens is None or question_tokens.size(1) == 0: pooled_question = torch.zeros_like(pooled_visual) else: normalized_question = self.model.scanflow_v2_intensity_question_norm( question_tokens ) pooled_question = normalized_question.mean(dim=1, keepdim=True).expand( -1, visual_tokens.size(1), -1 )
intensity_features = torch.cat( [intensity_visual, pooled_visual, pooled_question], dim=-1 ) reasoning_intensity = torch.sigmoid( self.model.scanflow_v2_intensity_mlp(intensity_features) ).to(dtype=visual_tokens.dtype) residual_visual_tokens = visual_tokens + reasoning_intensity * residual return residual, reasoning_intensity, residual_visual_tokens
def _project_text_tokens(self, text_context, device, dtype): if text_context is None: return None text_context = text_context.to(device=device) if text_context.dim() == 2: text_context = text_context.unsqueeze(1) elif text_context.dim() != 3: raise ValueError( f"text_context must have shape (B,D) or (B,L,D), got {tuple(text_context.shape)}." ) if text_context.size(-1) == self.text_hidden_dim: text_context = self.text_context_proj(text_context) elif text_context.size(-1) != self.hidden_dimension: raise ValueError( f"Unsupported text_context hidden size={text_context.size(-1)}; " f"expected {self.text_hidden_dim} or {self.hidden_dimension}." ) return text_context.to(dtype=dtype)
def _resolve_scanpath_steps(self, scanpath_lengths, scanpath_steps, device): if scanpath_steps is not None: steps = int(scanpath_steps) elif scanpath_lengths is not None: if not torch.is_tensor(scanpath_lengths): scanpath_lengths = torch.tensor(scanpath_lengths, device=device) steps = int(scanpath_lengths.to(device=device).max().item()) else: steps = self.max_scanpath_steps steps = max(1, steps) if steps > self.max_scanpath_steps: raise ValueError( f"scanpath_steps={steps} exceeds max_scanpath_steps={self.max_scanpath_steps}." ) return steps
def _build_scanpath_padding_mask(self, scanpath_lengths, batch_size, steps, device): if scanpath_lengths is None: return None if not torch.is_tensor(scanpath_lengths): scanpath_lengths = torch.tensor(scanpath_lengths, device=device) lengths = scanpath_lengths.to(device=device, dtype=torch.long).clamp(min=1, max=steps) step_ids = torch.arange(steps, device=device).unsqueeze(0) return step_ids.expand(batch_size, -1) >= lengths.unsqueeze(1)
@staticmethod def _extract_last_query_visual_attention( outputs, n_visual: int, layer_indices, ): """Return selected-layer [B,L_sel,H,N_visual] attention for newest state.
Qwen still has to compute attention weights for the forward when output_attentions=True, but recurrent Plan 1 retains only the four supervised middle layers across timesteps instead of retaining all decoder-layer attention tensors in the temporal supervision graph. """ attentions = getattr(outputs, "attentions", None) if attentions is None: return None
per_layer = [] for layer_idx in layer_indices: layer_attention = attentions[layer_idx] if layer_attention is None: return None # Qwen attention: [B,H,Q,K]. The newest recurrent state is the final # query position; visual tokens occupy keys [0:n_visual]. per_layer.append(layer_attention[:, :, -1, :n_visual])
# list([B,H,N]) -> [B,L_sel,H,N] return torch.stack(per_layer, dim=1)
def forward( self, x: torch.Tensor, text_context: Optional[torch.Tensor] = None, scanpath_lengths: Optional[torch.Tensor] = None, scanpath_steps: Optional[int] = None, collect_visual_attention: Optional[bool] = None, ) -> torch.Tensor: """Generate H recurrently, then apply the dynamic one-shot V2 residual.
x is the SAM feature map. Returned shape is [B,N+T,D] and is ordered as [V + lambda_i(V,Q)*R; H]. ``last_scanpath_hidden`` retains the checkpoint- compatible [B,T,D] reasoning sequence. """ visual_tokens = x.flatten(2).transpose(1, 2) batch_size, n_visual, _ = visual_tokens.shape device, dtype = visual_tokens.device, visual_tokens.dtype text_tokens = self._project_text_tokens(text_context, device, dtype) num_steps = self._resolve_scanpath_steps(scanpath_lengths, scanpath_steps, device) padding_mask = self._build_scanpath_padding_mask( scanpath_lengths, batch_size, num_steps, device )
# No learned causal query/token bank. The only bootstrap state is image # conditioned; every later seed is the actually generated previous state. prev_hidden = visual_tokens.mean(dim=1, keepdim=True) generated_states = [] visual_attn_steps = [] collect_attn = ( self.enable_attention_supervision if collect_visual_attention is None else bool(collect_visual_attention) )
for step_idx in range(num_steps): history = ( torch.cat(generated_states, dim=1) if generated_states else visual_tokens.new_zeros(batch_size, 0, self.hidden_dimension) ) current_seed = prev_hidden causal_inputs = torch.cat([history, current_seed], dim=1) n_causal = causal_inputs.size(1) # Preserve the original recurrent Plan-1 information flow exactly: # every h_t is generated against the same immutable V. The Version-2 # residual is deliberately absent from this temporal loop. combined = torch.cat([visual_tokens, causal_inputs], dim=1) token_type_ids = torch.cat([ torch.zeros(batch_size, n_visual, dtype=torch.long, device=device), torch.ones(batch_size, n_causal, dtype=torch.long, device=device), ], dim=1)
outputs = self.model( combined, token_type_ids, text_context=text_tokens, output_attentions=collect_attn, return_dict=True, use_cache=False, ) current_hidden = outputs.last_hidden_state[:, -1:, :] generated_states.append(current_hidden) prev_hidden = current_hidden
if collect_attn: step_visual_attn = self._extract_last_query_visual_attention( outputs, n_visual=n_visual, layer_indices=self.attention_supervision_layer_indices, ) if step_visual_attn is None: raise RuntimeError( "ScanFlow Pro V2 attention supervision was requested, but " "Qwen returned no visual self-attention weights." ) visual_attn_steps.append(step_visual_attn)
scanflow_debug_tensor(f"recurrent_plan1_step_{step_idx}_hidden", current_hidden)
scanpath_hidden = torch.cat(generated_states, dim=1) if padding_mask is not None: scanpath_hidden = scanpath_hidden.masked_fill(padding_mask.unsqueeze(-1), 0.0)
if visual_attn_steps: # Only the four supervised middle layers are retained: # list of [B,L_sel,H,N] -> [B,L_sel,T,H,N], L_sel=4. visual_attn_maps = torch.stack(visual_attn_steps, dim=2) if padding_mask is not None: visual_attn_maps = visual_attn_maps.masked_fill( padding_mask[:, None, :, None, None], 0.0 ) else: visual_attn_maps = None
reasoning_residual, reasoning_intensity, residual_visual_tokens = ( self._compute_global_reasoning_residual( visual_tokens=visual_tokens, scanpath_hidden=scanpath_hidden, scanpath_padding_mask=padding_mask, # Do not let the new V2 loss path update the trained Plan-1 text # projection. The gate still observes its question features; # Plan-1 continues to train through its unchanged recurrent path. question_tokens=( text_tokens.detach() if text_tokens is not None else None ), ) ) scanflow_output = torch.cat( [residual_visual_tokens, scanpath_hidden], dim=1 )
self.last_scanpath_hidden = scanpath_hidden self.last_reasoning_residual = reasoning_residual self.last_reasoning_intensity = reasoning_intensity self.last_residual_visual_tokens = residual_visual_tokens self.last_scanflow_output = scanflow_output self.last_visual_attn_maps = visual_attn_maps self.last_scanpath_mask = padding_mask self._scanflow_diagnostic_forward_step += 1 scanflow_log_attention_outputs( forward_step=self._scanflow_diagnostic_forward_step, visual_attn_maps=visual_attn_maps, ) scanflow_debug_tensor("recurrent_plan1_hidden", scanpath_hidden) scanflow_debug_tensor("scanflow_v2_reasoning_residual", reasoning_residual) scanflow_debug_tensor("scanflow_v2_reasoning_intensity", reasoning_intensity) scanflow_debug_tensor("scanflow_v2_residual_visual_tokens", residual_visual_tokens) scanflow_debug_tensor("scanflow_v2_output", scanflow_output) return scanflow_output
def build_qwen2_decoder_as_encoder( decoder_layer=24, hidden_dimension=896, num_attention_heads=14, num_key_value_heads=2, intermediate_size=4864, max_query = 400, text_hidden_dim=1280, max_scanpath_steps=32, scanpath_layers=2, scanpath_dropout=0.0, checkpoint=None,):
decoder_as_encoder = Qwen2Decoder2Encoder( decoder_layer=decoder_layer, hidden_dimension = hidden_dimension, num_attention_heads = num_attention_heads, num_key_value_heads = num_key_value_heads, intermediate_size = intermediate_size, max_query = max_query, text_hidden_dim=text_hidden_dim, max_scanpath_steps=max_scanpath_steps, scanpath_layers=scanpath_layers, scanpath_dropout=scanpath_dropout, )
if checkpoint is not None: # with open(checkpoint, "rb") as f: state_dict = torch.load(checkpoint)
load_result = decoder_as_encoder.load_state_dict(state_dict, strict=False) if load_result.missing_keys: print( "Missing keys when loading Qwen2Decoder2Encoder " f"({len(load_result.missing_keys)}): {load_result.missing_keys[:20]}" ) if load_result.unexpected_keys: print( "Unexpected keys when loading Qwen2Decoder2Encoder " f"({len(load_result.unexpected_keys)}): {load_result.unexpected_keys[:20]}" ) # tob print(checkpoint) return decoder_as_encoder
#=========================Sam-Vary=================================
def get_abs_pos_sam(abs_pos, tgt_size):
dtype = abs_pos.dtype
src_size = abs_pos.size(1)
if src_size != tgt_size: old_pos_embed = abs_pos.permute(0, 3, 1, 2) old_pos_embed = old_pos_embed.to(torch.float32) new_pos_embed = F.interpolate( old_pos_embed, size=(tgt_size, tgt_size), mode='bicubic', antialias=True, align_corners=False, ).to(dtype) new_pos_embed = new_pos_embed.permute(0, 2, 3, 1) return new_pos_embed else: return abs_pos
class MLPBlock(nn.Module): def __init__( self, embedding_dim: int, mlp_dim: int, act: Type[nn.Module] = nn.GELU, ) -> None: super().__init__() self.lin1 = nn.Linear(embedding_dim, mlp_dim) self.lin2 = nn.Linear(mlp_dim, embedding_dim) self.act = act()
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.lin2(self.act(self.lin1(x)))
# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqaclass LayerNorm2d(nn.Module): def __init__(self, num_channels: int, eps: float = 1e-6) -> None: super().__init__() self.weight = nn.Parameter(torch.ones(num_channels)) self.bias = nn.Parameter(torch.zeros(num_channels)) self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor: u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + self.eps) x = self.weight[:, None, None] * x + self.bias[:, None, None] return x
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqaclass ImageEncoderViT(nn.Module): def __init__( self, img_size: int = 1024, patch_size: int = 16, in_chans: int = 3, embed_dim: int = 768, depth: int = 12, num_heads: int = 12, mlp_ratio: float = 4.0, out_chans: int = 256, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_layer: Type[nn.Module] = nn.GELU, use_abs_pos: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, window_size: int = 0, global_attn_indexes: Tuple[int, ...] = (), ) -> None: """ Args: img_size (int): Input image size. patch_size (int): Patch size. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. depth (int): Depth of ViT. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_abs_pos (bool): If True, use absolute positional embeddings. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. global_attn_indexes (list): Indexes for blocks using global attention. """ super().__init__() self.img_size = img_size
self.patch_embed = PatchEmbed( kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), in_chans=in_chans, embed_dim=embed_dim, )
self.pos_embed: Optional[nn.Parameter] = None if use_abs_pos: # Initialize absolute positional embedding with pretrain image size. self.pos_embed = nn.Parameter( torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim) )
self.blocks = nn.ModuleList() for i in range(depth): block = Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, norm_layer=norm_layer, act_layer=act_layer, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, window_size=window_size if i not in global_attn_indexes else 0, input_size=(img_size // patch_size, img_size // patch_size), ) self.blocks.append(block)
self.neck = nn.Sequential( nn.Conv2d( embed_dim, out_chans, kernel_size=1, bias=False, ), LayerNorm2d(out_chans), nn.Conv2d( out_chans, out_chans, kernel_size=3, padding=1, bias=False, ), LayerNorm2d(out_chans), )
self.net_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1, bias=False) self.net_3 = nn.Conv2d(512, 896, kernel_size=3, stride=2, padding=1, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.patch_embed(x) if self.pos_embed is not None: # x = x + self.pos_embed x = x + get_abs_pos_sam(self.pos_embed, x.size(1))
for blk in self.blocks: x = blk(x)
x = self.neck(x.permute(0, 3, 1, 2)) x2 = self.net_2(x) x3 = self.net_3(x2.clone())
return x3
class Block(nn.Module): """Transformer blocks with support of window attention and residual propagation blocks"""
def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qkv_bias: bool = True, norm_layer: Type[nn.Module] = nn.LayerNorm, act_layer: Type[nn.Module] = nn.GELU, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, window_size: int = 0, input_size: Optional[Tuple[int, int]] = None, ) -> None: """ Args: dim (int): Number of input channels. num_heads (int): Number of attention heads in each ViT block. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool): If True, add a learnable bias to query, key, value. norm_layer (nn.Module): Normalization layer. act_layer (nn.Module): Activation layer. use_rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. window_size (int): Window size for window attention blocks. If it equals 0, then use global attention. input_size (tuple(int, int) or None): Input resolution for calculating the relative positional parameter size. """ super().__init__() self.norm1 = norm_layer(dim) self.attn = Attention( dim, num_heads=num_heads, qkv_bias=qkv_bias, use_rel_pos=use_rel_pos, rel_pos_zero_init=rel_pos_zero_init, input_size=input_size if window_size == 0 else (window_size, window_size), )
self.norm2 = norm_layer(dim) self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
self.window_size = window_size
def forward(self, x: torch.Tensor) -> torch.Tensor: shortcut = x x = self.norm1(x) # Window partition if self.window_size > 0: H, W = x.shape[1], x.shape[2] x, pad_hw = window_partition(x, self.window_size)
x = self.attn(x) # Reverse window partition if self.window_size > 0: x = window_unpartition(x, self.window_size, pad_hw, (H, W))
x = shortcut + x x = x + self.mlp(self.norm2(x))
return x
class Attention(nn.Module): """Multi-head Attention block with relative position embeddings."""
def __init__( self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_rel_pos: bool = False, rel_pos_zero_init: bool = True, input_size: Optional[Tuple[int, int]] = None, ) -> None: """ Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. qkv_bias (bool): If True, add a learnable bias to query, key, value. rel_pos (bool): If True, add relative positional embeddings to the attention map. rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. input_size (tuple(int, int) or None): Input resolution for calculating the relative positional parameter size. """ super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim)
self.use_rel_pos = use_rel_pos if self.use_rel_pos: assert ( input_size is not None ), "Input size must be provided if using relative positional encoding." # initialize relative positional embeddings self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
def forward(self, x: torch.Tensor) -> torch.Tensor: B, H, W, _ = x.shape # qkv with shape (3, B, nHead, H * W, C) qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) # q, k, v with shape (B * nHead, H * W, C) q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
rel_h, rel_w = None, None if self.use_rel_pos: rel_h, rel_w = add_decomposed_rel_pos(q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
q = q.view(B, self.num_heads, H * W, -1) k = k.view(B, self.num_heads, H * W, -1) v = v.view(B, self.num_heads, H * W, -1)
if self.use_rel_pos: rel_h = rel_h.view(B, self.num_heads, rel_h.size(1), rel_h.size(2), rel_h.size(3)) rel_w = rel_w.view(B, self.num_heads, rel_w.size(1), rel_w.size(2), rel_w.size(3)) attn_bias = (rel_h + rel_w).view(B, self.num_heads, rel_h.size(2), rel_h.size(3) * rel_w.size(4)) x = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attn_bias) # x = _attention_rel_h_rel_w(q, k, v, rel_h, rel_w) else: x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
x = x.view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
x = self.proj(x)
return x
def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: """ Partition into non-overlapping windows with padding if needed. Args: x (tensor): input tokens with [B, H, W, C]. window_size (int): window size.
Returns: windows: windows after partition with [B * num_windows, window_size, window_size, C]. (Hp, Wp): padded height and width before partition """ B, H, W, C = x.shape
pad_h = (window_size - H % window_size) % window_size pad_w = (window_size - W % window_size) % window_size if pad_h > 0 or pad_w > 0: x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) Hp, Wp = H + pad_h, W + pad_w
x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) return windows, (Hp, Wp)
def window_unpartition( windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]) -> torch.Tensor: """ Window unpartition into original sequences and removing padding. Args: windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. window_size (int): window size. pad_hw (Tuple): padded height and width (Hp, Wp). hw (Tuple): original height and width (H, W) before padding.
Returns: x: unpartitioned sequences with [B, H, W, C]. """ Hp, Wp = pad_hw H, W = hw B = windows.shape[0] // (Hp * Wp // window_size // window_size) x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
if Hp > H or Wp > W: x = x[:, :H, :W, :].contiguous() return x
def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: """ Get relative positional embeddings according to the relative positions of query and key sizes. Args: q_size (int): size of query q. k_size (int): size of key k. rel_pos (Tensor): relative position embeddings (L, C).
Returns: Extracted positional embeddings according to relative positions. """ max_rel_dist = int(2 * max(q_size, k_size) - 1) # Interpolate rel pos if needed. if rel_pos.shape[0] != max_rel_dist: # Interpolate rel pos. dtype = rel_pos.dtype rel_pos = rel_pos.to(torch.float32) rel_pos_resized = F.interpolate( rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear", ).to(dtype) rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) else: rel_pos_resized = rel_pos
# Scale the coords with short length if shapes for q and k are different. q_coords = torch.arange(q_size, device=rel_pos.device)[:, None] * max(k_size / q_size, 1.0) k_coords = torch.arange(k_size, device=rel_pos.device)[None, :] * max(q_size / k_size, 1.0) relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
return rel_pos_resized[relative_coords.long()]
def add_decomposed_rel_pos( q: torch.Tensor, rel_pos_h: torch.Tensor, rel_pos_w: torch.Tensor, q_size: Tuple[int, int], k_size: Tuple[int, int],) -> torch.Tensor: """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 Args: q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. q_size (Tuple): spatial sequence size of query q with (q_h, q_w). k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
Returns: attn (Tensor): attention map with added relative positional embeddings. """ q_h, q_w = q_size k_h, k_w = k_size Rh = get_rel_pos(q_h, k_h, rel_pos_h) Rw = get_rel_pos(q_w, k_w, rel_pos_w)
B, _, dim = q.shape r_q = q.reshape(B, q_h, q_w, dim) rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) rel_h = rel_h.unsqueeze(-1) rel_w = rel_w.unsqueeze(-2) rel_h = rel_h.reshape(B, q_h * q_w, k_h, 1) rel_w = rel_w.reshape(B, q_h * q_w, 1, k_w)
return rel_h, rel_w
class PatchEmbed(nn.Module): """ Image to Patch Embedding. """
def __init__( self, kernel_size: Tuple[int, int] = (16, 16), stride: Tuple[int, int] = (16, 16), padding: Tuple[int, int] = (0, 0), in_chans: int = 3, embed_dim: int = 768, ) -> None: """ Args: kernel_size (Tuple): kernel size of the projection layer. stride (Tuple): stride of the projection layer. padding (Tuple): padding size of the projection layer. in_chans (int): Number of input image channels. embed_dim (int): Patch embedding dimension. """ super().__init__()
self.proj = nn.Conv2d( in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding )
# def forward(self, x: torch.Tensor) -> torch.Tensor: # x = self.proj(x) # # B C H W -> B H W C # x = x.permute(0, 2, 3, 1) # return x
def forward(self, x: torch.Tensor) -> torch.Tensor: dtype = self.proj.weight.dtype x = x.to(device=self.proj.weight.device, dtype=dtype) if self.proj.bias is not None and self.proj.bias.dtype != dtype: self.proj.bias.data = self.proj.bias.data.to(dtype) x = self.proj(x) return x.permute(0, 2, 3, 1)
def build_sam_vit_b(checkpoint=None): return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], checkpoint=checkpoint, )
def build_sam_fast_vit_b(checkpoint=None, compile_mode='max-autotune', dtype=torch.bfloat16): image_encoder = build_sam_vit_b(checkpoint).eval().to(dtype) # sam = _apply_eval_dtype_sam(sam, dtype) image_encoder = torch.compile(image_encoder, mode=compile_mode) return image_encoder
def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None,): prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size image_encoder=ImageEncoderViT( depth=encoder_depth, embed_dim=encoder_embed_dim, img_size=image_size, mlp_ratio=4, norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), num_heads=encoder_num_heads, patch_size=vit_patch_size, qkv_bias=True, use_rel_pos=True, global_attn_indexes=encoder_global_attn_indexes, window_size=14, out_chans=prompt_embed_dim, ) image_encoder.eval() if checkpoint is not None: # with open(checkpoint, "rb") as f: state_dict = torch.load(checkpoint) # print(state_dict.keys()) # for key in state_dict: # image_encoder.load_state_dict({k[14:]: v for k, v in state_dict.items() if 'image_encoder' in k}, strict=False) # ocr-anyting # image_encoder.load_state_dict(state_dict, strict=True) # tob image_encoder.load_state_dict({k[30:]: v for k, v in state_dict.items() if 'vision_tower_high' in k}, strict=True) print(checkpoint) return image_encoder123456{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 1, "transformers_version": "4.46.3"}123version https://git-lfs.github.com/spec/v1oid sha256:7964e819626e34eaa827751ab2bd546189534d8ee12e064e93a18a95002b58e8size 5000040704123version https://git-lfs.github.com/spec/v1oid sha256:1e809c90d66b1d4580c6cfbb8158ae93cf3378881e1b0e35547cd1fe431c4f8esize 19457956261234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110from .modeling_deepseekv2 import DeepseekV2Model, DeepseekV2ForCausalLMfrom .configuration_deepseek_v2 import DeepseekV2Configfrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPastfrom typing import List, Optional, Tuple, Unionfrom transformers.cache_utils import Cacheimport requestsfrom PIL import Image, ImageOps, ImageDraw, ImageFontfrom io import BytesIOimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.nn import CrossEntropyLossfrom torchvision import transforms# from torchvision.transforms.functional import InterpolationModeimport osfrom .deepencoderv2 import build_sam_vit_b, build_qwen2_decoder_as_encoder, MlpProjectorfrom addict import Dictfrom transformers import TextStreamerfrom .conversation import get_conv_templatefrom abc import ABCimport mathimport refrom tqdm import tqdmimport numpy as np# import time
def scanflow_debug_tensor(name, x): if x is None: print(f"[scanflow debug] {name}: None", flush=True) return
try: t = x.detach() finite = torch.isfinite(t) if torch.is_floating_point(t) else torch.ones_like(t, dtype=torch.bool) finite_count = int(finite.sum().item()) total = t.numel()
msg = ( f"[scanflow debug] {name}: " f"shape={tuple(t.shape)} dtype={t.dtype} device={t.device} " f"finite={finite_count}/{total}" )
if torch.is_floating_point(t) and finite_count > 0: tf = t[finite] msg += ( f" min={tf.min().item():.6g}" f" max={tf.max().item():.6g}" f" mean={tf.float().mean().item():.6g}" )
print(msg, flush=True) except Exception as exc: print(f"[scanflow debug] {name}: failed to summarize: {exc}", flush=True)
def load_image(image_path):
try: image = Image.open(image_path) corrected_image = ImageOps.exif_transpose(image) return corrected_image except Exception as e: print(f"error: {e}") try: return Image.open(image_path) except: return None
def re_match(text): pattern = r'(<\|ref\|>(.*?)<\|/ref\|><\|det\|>(.*?)<\|/det\|>)' matches = re.findall(pattern, text, re.DOTALL)
# pattern1 = r'<\|ref\|>.*?<\|/ref\|>\n' # new_text1 = re.sub(pattern1, '', text, flags=re.DOTALL)
mathes_image = [] mathes_other = [] for a_match in matches: if '<|ref|>image<|/ref|>' in a_match[0]: mathes_image.append(a_match[0]) else: mathes_other.append(a_match[0]) return matches, mathes_image, mathes_other
def extract_coordinates_and_label(ref_text, image_width, image_height):
try: label_type = ref_text[1] cor_list = eval(ref_text[2]) except Exception as e: print(e) return None
return (label_type, cor_list)
def draw_bounding_boxes(image, refs, ouput_path):
image_width, image_height = image.size img_draw = image.copy() draw = ImageDraw.Draw(img_draw)
overlay = Image.new('RGBA', img_draw.size, (0, 0, 0, 0)) draw2 = ImageDraw.Draw(overlay) # try: # except IOError: # try: # font = ImageFont.truetype("DejaVuSans.ttf", 20) # except IOError: font = ImageFont.load_default()
img_idx = 0 for i, ref in enumerate(refs): try: result = extract_coordinates_and_label(ref, image_width, image_height) if result: label_type, points_list = result color = (np.random.randint(0, 200), np.random.randint(0, 200), np.random.randint(0, 255))
color_a = color + (20, ) for points in points_list: x1, y1, x2, y2 = points
x1 = int(x1 / 999 * image_width) y1 = int(y1 / 999 * image_height)
x2 = int(x2 / 999 * image_width) y2 = int(y2 / 999 * image_height)
if label_type == 'image': try: cropped = image.crop((x1, y1, x2, y2)) cropped.save(f"{ouput_path}/images/{img_idx}.jpg") except Exception as e: print(e) pass img_idx += 1 try: if label_type == 'title': draw.rectangle([x1, y1, x2, y2], outline=color, width=4) draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1) else: draw.rectangle([x1, y1, x2, y2], outline=color, width=2) draw2.rectangle([x1, y1, x2, y2], fill=color_a, outline=(0, 0, 0, 0), width=1) text_x = x1 text_y = max(0, y1 - 15) text_bbox = draw.textbbox((0, 0), label_type, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] draw.rectangle([text_x, text_y, text_x + text_width, text_y + text_height], fill=(255, 255, 255, 30)) draw.text((text_x, text_y), label_type, font=font, fill=color) except: pass except: continue img_draw.paste(overlay, (0, 0), overlay) return img_draw
def process_image_with_refs(image, ref_texts, output_path):
result_image = draw_bounding_boxes(image, ref_texts, output_path) return result_image
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): best_ratio_diff = float('inf') best_ratio = (1, 1) area = width * height for ratio in target_ratios: target_aspect_ratio = ratio[0] / ratio[1] ratio_diff = abs(aspect_ratio - target_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_ratio = ratio elif ratio_diff == best_ratio_diff: if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: best_ratio = ratio # print(f'width: {width}, height: {height}, best_ratio: {best_ratio}') return best_ratio
def dynamic_preprocess(image, min_num=2, max_num=6, image_size=768, use_thumbnail=False): orig_width, orig_height = image.size aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio target_ratios = set( (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num) # print(target_ratios) target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target target_aspect_ratio = find_closest_aspect_ratio( aspect_ratio, target_ratios, orig_width, orig_height, image_size)
# print(target_aspect_ratio) # calculate the target width and height target_width = image_size * target_aspect_ratio[0] target_height = image_size * target_aspect_ratio[1] blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
# resize the image resized_img = image.resize((target_width, target_height)) processed_images = [] for i in range(blocks): box = ( (i % (target_width // image_size)) * image_size, (i // (target_width // image_size)) * image_size, ((i % (target_width // image_size)) + 1) * image_size, ((i // (target_width // image_size)) + 1) * image_size ) # split the image split_img = resized_img.crop(box) processed_images.append(split_img) assert len(processed_images) == blocks if use_thumbnail and len(processed_images) != 1: thumbnail_img = image.resize((image_size, image_size)) processed_images.append(thumbnail_img) return processed_images, target_aspect_ratio
def normalize_transform(mean, std): if mean is None and std is None: transform = None elif mean is None and std is not None: mean = [0.] * len(std) transform = transforms.Normalize(mean=mean, std=std) elif mean is not None and std is None: std = [1.] * len(mean) transform = transforms.Normalize(mean=mean, std=std) else: transform = transforms.Normalize(mean=mean, std=std)
return transform
def format_messages( conversations: List[Dict[str, str]], sft_format: str = "deepseek", system_prompt: str = "",): """ Applies the SFT template to conversation.
Args: conversations (List[Dict]): A List of messages. sft_format (str, optional): The format of the SFT template to use. Defaults to "deepseek". system_prompt (str, optional): The system prompt to use in the SFT template. Defaults to "".
Returns: sft_prompt (str): The formatted text. """
conv = get_conv_template(sft_format) conv.set_system_message(system_prompt) for message in conversations: conv.append_message(message["role"], message["content"].strip()) sft_prompt = conv.get_prompt().strip()
return sft_prompt
def text_encode(tokenizer, text: str, bos: bool = True, eos: bool = False): t = tokenizer.encode(text, add_special_tokens=False) bos_id = 0 eos_id = 1 if bos: t = [bos_id] + t if eos: t = t + [eos_id]
return t
def load_pil_images(conversations: List[Dict[str, str]]) -> List[Image.Image]: """
Args: conversations (List[Dict[str, str]]): the conversations with a list of messages. An example is : [ { "role": "User", "content": "<image_placeholder>\nExtract all information from this image and convert them into markdown format.", "images": ["./examples/table_datasets.png"] }, {"role": "Assistant", "content": ""}, ]
Returns: pil_images (List[PIL.Image.Image]): the list of PIL images.
"""
pil_images = []
for message in conversations: if "images" not in message: continue
for image_path in message["images"]: # print('----------------') # print(image_path) # print('----------------') # exit() # pil_img = Image.open(image_path) pil_img = load_image(image_path) pil_img = pil_img.convert("RGB") pil_images.append(pil_img)
return pil_images
class BaseTransform(ABC):
def set_rng(self, *args, **kwargs): pass
def __call__(self, *args, **kwargs) -> torch.Tensor: pass
@property def default_shape(self): raise NotImplementedError
class BasicImageTransform(BaseTransform): def __init__( self, mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5), std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5), normalize: bool = True ): self.mean = mean self.std = std transform_pipelines = [ transforms.ToTensor() ]
normalize = normalize_transform(mean, std) if normalize else nn.Identity() if normalize is not None: transform_pipelines.append(normalize)
self.transform = transforms.Compose(transform_pipelines) def __call__(self, x): x = self.transform(x) return x
class NoEOSTextStreamer(TextStreamer): def on_finalized_text(self, text: str, stream_end: bool = False):
eos_text = self.tokenizer.decode([self.tokenizer.eos_token_id], skip_special_tokens=False) text = text.replace(eos_text, "\n") print(text, flush=True, end="")
class DeepseekOCR2Config(DeepseekV2Config): model_type = "DeepseekOCR2"
def scanpath_fixation_loss( fixation_logits: torch.Tensor, fixation_targets: torch.Tensor, fixation_mask: torch.Tensor,) -> torch.Tensor: """ Computes soft-label cross entropy over visual patch fixation distributions.
fixation_logits: [B, T, N] fixation_targets: [B, T_max, N] fixation_mask: [B, T_max] """ if fixation_logits.size(-1) != fixation_targets.size(-1): raise ValueError( f"Fixation token mismatch: logits have {fixation_logits.size(-1)} tokens, " f"targets have {fixation_targets.size(-1)} tokens." )
steps = fixation_logits.size(1) fixation_targets = fixation_targets[:, :steps, :].to( device=fixation_logits.device, dtype=torch.float32, ) fixation_mask = fixation_mask[:, :steps].to( device=fixation_logits.device, dtype=torch.float32, )
log_probs = F.log_softmax(fixation_logits.float(), dim=-1) per_step_loss = -(fixation_targets * log_probs).sum(dim=-1)
return (per_step_loss * fixation_mask).sum() / fixation_mask.sum().clamp_min(1.0)
def scanpath_resize_distribution_to_target_tokens( distribution: torch.Tensor, target_tokens: int, eps: float = 1e-8,) -> torch.Tensor: """ Resize a flattened spatial distribution to the target token count.
distribution: [B, T, N] target_tokens: usually 256 for the SalChartQA 16x16 global fixation grid.
If N already matches target_tokens, this returns the normalized input. If both N and target_tokens are square grids, it bilinearly resamples the distribution spatially and renormalizes. This keeps attention supervision compatible with 144-token and 256-token visual grids without changing the original model path. """ distribution = distribution.float() distribution = distribution / distribution.sum(dim=-1, keepdim=True).clamp_min(eps)
source_tokens = distribution.size(-1) if source_tokens == target_tokens: return distribution
source_side = int(math.sqrt(source_tokens)) target_side = int(math.sqrt(target_tokens)) if source_side * source_side != source_tokens or target_side * target_side != target_tokens: raise ValueError( f"Cannot resize attention distribution from {source_tokens} to {target_tokens} tokens; " "both token counts must be square grids." )
batch_size, steps, _ = distribution.shape distribution_2d = distribution.reshape(batch_size * steps, 1, source_side, source_side) resized = F.interpolate( distribution_2d, size=(target_side, target_side), mode="bilinear", align_corners=False, ) resized = resized.reshape(batch_size, steps, target_tokens).clamp_min(0.0) return resized / resized.sum(dim=-1, keepdim=True).clamp_min(eps)
def scanpath_attention_alignment_loss( visual_attn_maps: torch.Tensor, fixation_targets: torch.Tensor, fixation_mask: torch.Tensor, eps: float = 1e-8,) -> torch.Tensor: """ Align the four supervised middle recurrent-Qwen layers with human fixations.
visual_attn_maps: [B, L_sel, T, H, N] L_sel = 4 selected middle Qwen layers (10,11,12,13 for a 24-layer model). H = all query attention heads (14 in the current Qwen configuration).
Supervision is intentionally applied in two stages: 1. Within EACH selected layer, average over ALL attention heads: p_l,t = mean_h A_l,t,h 2. Compute the fixation soft cross-entropy independently for each layer, then average the four layer losses.
This means every selected middle layer must itself exhibit temporally aligned visual attention; averaging layers before the loss cannot let one layer hide another layer's mismatch. """ if visual_attn_maps is None: raise ValueError("visual_attn_maps is None.") if visual_attn_maps.dim() != 5: raise ValueError( f"Expected visual_attn_maps to have shape [B, L_sel, T, H, N], " f"got {tuple(visual_attn_maps.shape)}." ) if visual_attn_maps.size(1) != 4: raise ValueError( "Middle-four attention supervision expects exactly 4 retained layers, " f"got {visual_attn_maps.size(1)}." )
# Mean across ALL heads independently within each selected layer. # [B,4,T,H,N] -> [B,4,T,N] pred_by_layer = visual_attn_maps.float().mean(dim=3) pred_by_layer = pred_by_layer / pred_by_layer.sum( dim=-1, keepdim=True ).clamp_min(eps)
steps = pred_by_layer.size(2) targets = fixation_targets[:, :steps, :].to( device=pred_by_layer.device, dtype=torch.float32, ) mask = fixation_mask[:, :steps].to( device=pred_by_layer.device, dtype=torch.float32, ) targets = targets / targets.sum(dim=-1, keepdim=True).clamp_min(eps)
layer_losses = [] for layer_slot in range(pred_by_layer.size(1)): pred = pred_by_layer[:, layer_slot] # [B,T,N]
if pred.size(-1) != targets.size(-1): pred = scanpath_resize_distribution_to_target_tokens( pred, target_tokens=targets.size(-1), eps=eps, )
per_step_loss = -( targets * pred.clamp_min(eps).log() ).sum(dim=-1) layer_loss = ( (per_step_loss * mask).sum() / mask.sum().clamp_min(1.0) ) layer_losses.append(layer_loss)
# Equal supervision strength for each of the four middle layers. return torch.stack(layer_losses).mean()
def scanpath_attention_entropy_metrics( visual_attn_maps: torch.Tensor, fixation_targets: torch.Tensor, fixation_mask: torch.Tensor, eps: float = 1e-12,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Diagnostics matching the middle-four/all-head attention objective.
Prediction entropy and excess cross entropy are computed independently for each supervised layer after averaging all heads, then averaged across the four layers. Target entropy is shared by all layers. """ if visual_attn_maps is None: raise ValueError("visual_attn_maps is None.") if visual_attn_maps.dim() != 5: raise ValueError( f"Expected visual_attn_maps to have shape [B, L_sel, T, H, N], " f"got {tuple(visual_attn_maps.shape)}." ) if visual_attn_maps.size(1) != 4: raise ValueError( "Middle-four attention diagnostics expect exactly 4 retained layers, " f"got {visual_attn_maps.size(1)}." )
pred_by_layer = visual_attn_maps.float().mean(dim=3) # [B,4,T,N] pred_by_layer = pred_by_layer / pred_by_layer.sum( dim=-1, keepdim=True ).clamp_min(eps)
steps = pred_by_layer.size(2) targets = fixation_targets[:, :steps, :].to( device=pred_by_layer.device, dtype=torch.float32, ) mask = fixation_mask[:, :steps].to( device=pred_by_layer.device, dtype=torch.float32, ) targets = targets / targets.sum(dim=-1, keepdim=True).clamp_min(eps)
target_entropy_per_step = -( targets * targets.clamp_min(eps).log() ).sum(dim=-1) normalizer = mask.sum().clamp_min(1.0) target_entropy = ( target_entropy_per_step * mask ).sum() / normalizer
layer_prediction_entropies = [] layer_excess_cross_entropies = []
for layer_slot in range(pred_by_layer.size(1)): pred = pred_by_layer[:, layer_slot]
if pred.size(-1) != targets.size(-1): pred = scanpath_resize_distribution_to_target_tokens( pred, target_tokens=targets.size(-1), eps=eps, )
log_pred = pred.clamp_min(eps).log() pred_entropy_per_step = -(pred * log_pred).sum(dim=-1) cross_entropy_per_step = -(targets * log_pred).sum(dim=-1) excess_ce_per_step = ( cross_entropy_per_step - target_entropy_per_step ).clamp_min(0.0)
layer_prediction_entropies.append( (pred_entropy_per_step * mask).sum() / normalizer ) layer_excess_cross_entropies.append( (excess_ce_per_step * mask).sum() / normalizer )
prediction_entropy = torch.stack(layer_prediction_entropies).mean() excess_cross_entropy = torch.stack(layer_excess_cross_entropies).mean() return target_entropy, prediction_entropy, excess_cross_entropy
def scanpath_fixation_entropy_metrics( fixation_logits: torch.Tensor, fixation_targets: torch.Tensor, fixation_mask: torch.Tensor, eps: float = 1e-12,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Computes masked mean entropy diagnostics for ScanFlow fixation prediction.
Returns: target_entropy: H(y) = -sum_i y_i log y_i. This is the theoretical minimum soft-label cross entropy for the supplied target distributions.
prediction_entropy: H(p) = -sum_i p_i log p_i. Lower values indicate sharper model predictions; higher values indicate broader or more uniform maps.
excess_cross_entropy: CE(y, p) - H(y) = KL(y || p). This is the portion of the fixation cross entropy caused by prediction-target mismatch rather than the irreducible entropy of the Gaussian target itself.
Shapes: fixation_logits: [B, T, N] fixation_targets: [B, T_max, N] fixation_mask: [B, T_max] """ if fixation_logits.size(-1) != fixation_targets.size(-1): raise ValueError( f"Entropy token mismatch: logits have {fixation_logits.size(-1)} tokens, " f"targets have {fixation_targets.size(-1)} tokens." )
steps = fixation_logits.size(1) targets = fixation_targets[:, :steps, :].to( device=fixation_logits.device, dtype=torch.float32, ) mask = fixation_mask[:, :steps].to( device=fixation_logits.device, dtype=torch.float32, )
# Normalize defensively in case preprocessing introduces small numerical # deviations from an exact row sum of one. targets = targets / targets.sum(dim=-1, keepdim=True).clamp_min(eps)
log_probs = F.log_softmax(fixation_logits.float(), dim=-1) probs = log_probs.exp()
per_step_target_entropy = -( targets * targets.clamp_min(eps).log() ).sum(dim=-1)
per_step_prediction_entropy = -( probs * log_probs ).sum(dim=-1)
per_step_cross_entropy = -( targets * log_probs ).sum(dim=-1)
per_step_excess_cross_entropy = ( per_step_cross_entropy - per_step_target_entropy ).clamp_min(0.0)
normalizer = mask.sum().clamp_min(1.0)
target_entropy = ( per_step_target_entropy * mask ).sum() / normalizer
prediction_entropy = ( per_step_prediction_entropy * mask ).sum() / normalizer
excess_cross_entropy = ( per_step_excess_cross_entropy * mask ).sum() / normalizer
return target_entropy, prediction_entropy, excess_cross_entropy
def scanpath_diversity_loss( fixation_logits: torch.Tensor, fixation_targets: torch.Tensor, fixation_mask: torch.Tensor, eps: float = 1e-8,) -> torch.Tensor: """ Target-conditioned pairwise diversity loss.
The loss penalizes predicted fixation distributions for being similar when the corresponding ground-truth fixation distributions are different.
fixation_logits: [B, T, N] fixation_targets: [B, T_max, N] fixation_mask: [B, T_max]
This is intentionally applied to predicted fixation distributions rather than raw hidden states so that diversity must affect the fixation output. """ if fixation_logits.size(-1) != fixation_targets.size(-1): raise ValueError( f"Diversity token mismatch: logits have {fixation_logits.size(-1)} tokens, " f"targets have {fixation_targets.size(-1)} tokens." )
steps = fixation_logits.size(1) if steps <= 1: return fixation_logits.sum() * 0.0
predictions = F.softmax(fixation_logits.float(), dim=-1) targets = fixation_targets[:, :steps, :].to( device=fixation_logits.device, dtype=torch.float32, ) mask = fixation_mask[:, :steps].to( device=fixation_logits.device, dtype=torch.float32, )
pred_norm = F.normalize(predictions, p=2, dim=-1, eps=eps) target_norm = F.normalize(targets, p=2, dim=-1, eps=eps)
pred_similarity = torch.matmul(pred_norm, pred_norm.transpose(1, 2)) target_similarity = torch.matmul(target_norm, target_norm.transpose(1, 2))
pair_mask = mask.unsqueeze(2) * mask.unsqueeze(1) diagonal = torch.eye( steps, device=fixation_logits.device, dtype=pair_mask.dtype, ).unsqueeze(0) pair_mask = pair_mask * (1.0 - diagonal)
# Pairs with similar target maps receive little or no diversity penalty. target_difference = (1.0 - target_similarity).clamp_min(0.0).detach() weights = pair_mask * target_difference
weighted_similarity = weights * pred_similarity normalizer = weights.sum().clamp_min(eps) return weighted_similarity.sum() / normalizer
def scanflow_loss_gradients( loss: Optional[torch.Tensor], parameters: list[torch.nn.Parameter],) -> list[Optional[torch.Tensor]]: """Return gradients for one loss without modifying parameter.grad.""" if loss is None or not torch.is_tensor(loss) or not loss.requires_grad: return [None] * len(parameters) return list(torch.autograd.grad( loss, parameters, retain_graph=True, create_graph=False, allow_unused=True, ))
def scanflow_gradient_norm( gradients: list[Optional[torch.Tensor]],) -> torch.Tensor: total = None for grad in gradients: if grad is None: continue value = grad.detach().float().pow(2).sum() total = value if total is None else total + value return torch.tensor(0.0) if total is None else total.sqrt()
def scanflow_gradient_dot( gradients_a: list[Optional[torch.Tensor]], gradients_b: list[Optional[torch.Tensor]],) -> torch.Tensor: total = None for grad_a, grad_b in zip(gradients_a, gradients_b): if grad_a is None or grad_b is None: continue value = (grad_a.detach().float() * grad_b.detach().float()).sum() total = value if total is None else total + value return torch.tensor(0.0) if total is None else total
def scanflow_gradient_cosine( gradients_a: list[Optional[torch.Tensor]], gradients_b: list[Optional[torch.Tensor]], eps: float = 1e-12,) -> torch.Tensor: norm_a = scanflow_gradient_norm(gradients_a) norm_b = scanflow_gradient_norm(gradients_b) denominator = norm_a * norm_b if float(denominator.detach().cpu()) <= eps: return torch.tensor(float("nan")) return scanflow_gradient_dot(gradients_a, gradients_b) / denominator
def scanflow_weighted_combined_gradient_norm( gradient_groups: list[tuple[float, list[Optional[torch.Tensor]]]],) -> torch.Tensor: if not gradient_groups: return torch.tensor(0.0) total_sq = None for parameter_index in range(len(gradient_groups[0][1])): combined = None for weight, gradients in gradient_groups: grad = gradients[parameter_index] if grad is None or weight == 0.0: continue term = grad.detach().float() * float(weight) combined = term if combined is None else combined + term if combined is None: continue value = combined.pow(2).sum() total_sq = value if total_sq is None else total_sq + value return torch.tensor(0.0) if total_sq is None else total_sq.sqrt()
def scanflow_is_main_process() -> bool: return not ( torch.distributed.is_available() and torch.distributed.is_initialized() and torch.distributed.get_rank() != 0 )
def scanflow_diagnostic_patterns() -> tuple[str, ...]: raw = os.getenv( "DEEPSEEK_OCR2_UPDATE_PARAM_FILTER", "qwen2_model.model.model,qwen2_model.model.text_cross_norms," "qwen2_model.model.text_cross_attn_layers,qwen2_model.text_context_proj", ) return tuple(part.strip() for part in raw.split(",") if part.strip())
class DeepseekOCR2Model(DeepseekV2Model): """DeepSeek-OCR2 outer model for dynamic ScanFlow Pro V2.
The visual encoder preserves the recurrent Plan-1 generation of h_1...h_T, all against the immutable visual tokens V. After H is complete, V queries H once to produce R. A tokenwise reasoning-intensity gate lambda_i(V,Q) then produces [V + lambda(V,Q)*R; H]. Human scanpath supervision remains attached to the same Qwen self-attention h_t -> V maps on the GLOBAL image branch. """
config_class = DeepseekOCR2Config
def __init__(self, config: DeepseekV2Config): super(DeepseekOCR2Model, self).__init__(config) self.sam_model = build_sam_vit_b() self.qwen2_model = build_qwen2_decoder_as_encoder(max_scanpath_steps=32) n_embed = 1280 self.projector = MlpProjector( Dict(projector_type="linear", input_dim=896, n_embed=n_embed) ) embed_std = 1 / torch.sqrt(torch.tensor(n_embed, dtype=torch.float32)) self.view_seperator = nn.Parameter(torch.randn(n_embed) * embed_std)
# Compatibility attributes used by older training/evaluation scripts. # Recurrence and the V2 global residual are intrinsic to qwen2_model. self.enable_scanflow = True self.enable_text_query_residual = True self.last_visual_attn_maps = None self.last_visual_attn_layer_indices = tuple( getattr(self.qwen2_model, "attention_supervision_layer_indices", ()) )
# Reset is intentionally deferred until the first real forward pass. # Hugging Face/MS-Swift constructs the module first and loads checkpoint # tensors afterward; resetting inside __init__ would therefore be # overwritten by from_pretrained(). self._scanflow_new_params_reset_done = False self._scanflow_v2_new_params_reset_done = False
def _select_text_context( self, inputs_embeds: torch.Tensor, sample_idx: int, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, images_seq_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: # The question context conditions the visual/recurrent encoder, but we do # not need gradients back into the outer LLM token embeddings through this # auxiliary branch. token_source = inputs_embeds[sample_idx].detach() mask = torch.ones(token_source.shape[0], dtype=torch.bool, device=token_source.device) if attention_mask is not None: mask = mask & attention_mask[sample_idx].bool() if images_seq_mask is not None: mask = mask & (~images_seq_mask[sample_idx].bool()) if labels is not None: prompt_mask = mask & labels[sample_idx].eq(-100) if prompt_mask.sum() > 0: mask = prompt_mask if mask.sum() == 0: mask = torch.ones_like(mask) return token_source[mask].unsqueeze(0)
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, images: Optional[torch.FloatTensor] = None, images_seq_mask: Optional[torch.FloatTensor] = None, images_spatial_crop: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, return_dict: Optional[bool] = None, scanpath_lengths: Optional[torch.Tensor] = None, scanpath_steps: Optional[int] = None, ) -> Union[Tuple, BaseModelOutputWithPast]: # Original recurrent Plan-1 reset mechanism. Keep this switch off when # starting V2 from an already-trained Plan-1 recurrent checkpoint. if ( not self._scanflow_new_params_reset_done and os.getenv("SCANFLOW_RESET_NEW_PARAMS", "0").strip().lower() in {"1", "true", "yes", "on"} ): qwen2_model_for_reset = getattr(self, "qwen2_model", None) if qwen2_model_for_reset is None or not hasattr( qwen2_model_for_reset, "reset_scanflow_parameters" ): raise RuntimeError( "SCANFLOW_RESET_NEW_PARAMS=1, but qwen2_model does not expose " "reset_scanflow_parameters()." ) qwen2_model_for_reset.reset_scanflow_parameters() self._scanflow_new_params_reset_done = True
# Independent Version-2 reset mechanism. For the first transition from # a Plan-1 checkpoint, this initializes only R=CrossAttn(V,H,H) and its # question-conditioned tokenwise intensity head, leaving every trained # Plan-1 parameter untouched. if ( not self._scanflow_v2_new_params_reset_done and os.getenv("SCANFLOW_V2_RESET_NEW_PARAMS", "0").strip().lower() in {"1", "true", "yes", "on"} ): qwen2_model_for_reset = getattr(self, "qwen2_model", None) if qwen2_model_for_reset is None or not hasattr( qwen2_model_for_reset, "reset_scanflow_v2_parameters" ): raise RuntimeError( "SCANFLOW_V2_RESET_NEW_PARAMS=1, but qwen2_model does not " "expose reset_scanflow_v2_parameters()." ) qwen2_model_for_reset.reset_scanflow_v2_parameters() self._scanflow_v2_new_params_reset_done = True
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
sam_model = getattr(self, "sam_model", None) qwen2_model = getattr(self, "qwen2_model", None) self.last_visual_attn_maps = None self.last_visual_attn_layer_indices = tuple( getattr(qwen2_model, "attention_supervision_layer_indices", ()) ) batch_visual_attn_maps = []
if ( sam_model is not None and qwen2_model is not None and (input_ids.shape[1] != 1 or self.training) and torch.sum(images[0][1]).item() != 0 ): idx = 0 for image, crop_shape in zip(images, images_spatial_crop): del crop_shape patches = image[0] image_ori = image[1]
sample_scanpath_lengths = None if scanpath_lengths is not None: sample_scanpath_lengths = scanpath_lengths[idx:idx + 1]
# ScanFlow Pro V2 uses a genuinely dynamic number of causal states. # During training use the sample's true length; at inference, None # lets qwen2_model fall back to max_scanpath_steps=32. if scanpath_steps is not None: sample_scanpath_steps = int(scanpath_steps) elif sample_scanpath_lengths is not None: sample_scanpath_steps = int(sample_scanpath_lengths.max().item()) else: sample_scanpath_steps = None
sample_text_context = self._select_text_context( inputs_embeds, idx, attention_mask=attention_mask, labels=labels, images_seq_mask=images_seq_mask, )
if torch.sum(patches).item() != 0: with torch.no_grad(): local_features_1 = sam_model(patches) global_features_1 = sam_model(image_ori)
local_text_context = sample_text_context.expand( local_features_1.shape[0], -1, -1 ) global_text_context = sample_text_context.expand( global_features_1.shape[0], -1, -1 ) local_scanpath_lengths = ( sample_scanpath_lengths.expand(local_features_1.shape[0]) if sample_scanpath_lengths is not None else None ) global_scanpath_lengths = ( sample_scanpath_lengths.expand(global_features_1.shape[0]) if sample_scanpath_lengths is not None else None )
# Every view returns [V + lambda(V,Q)*R; H]. The residual and # tokenwise intensity are computed once after H; only the # global branch retains Qwen attention maps for scanpath loss. local_features_2 = qwen2_model( local_features_1, text_context=local_text_context, scanpath_lengths=local_scanpath_lengths, scanpath_steps=sample_scanpath_steps, collect_visual_attention=False, ) local_features = self.projector(local_features_2)
global_features_2 = qwen2_model( global_features_1, text_context=global_text_context, scanpath_lengths=global_scanpath_lengths, scanpath_steps=sample_scanpath_steps, collect_visual_attention=getattr( qwen2_model, "enable_attention_supervision", False ), ) global_visual_attn_maps = getattr( qwen2_model, "last_visual_attn_maps", None ) if global_visual_attn_maps is not None: batch_visual_attn_maps.append(global_visual_attn_maps) global_features = self.projector(global_features_2)
local_features = local_features.reshape(-1, local_features.size(-1)) global_features = global_features.reshape(-1, global_features.size(-1)) global_local_features = torch.cat( [local_features, global_features, self.view_seperator[None, :]], dim=0, ) else: with torch.no_grad(): global_features_1 = sam_model(image_ori) global_text_context = sample_text_context.expand( global_features_1.shape[0], -1, -1 ) global_scanpath_lengths = ( sample_scanpath_lengths.expand(global_features_1.shape[0]) if sample_scanpath_lengths is not None else None ) global_features_2 = qwen2_model( global_features_1, text_context=global_text_context, scanpath_lengths=global_scanpath_lengths, scanpath_steps=sample_scanpath_steps, collect_visual_attention=getattr( qwen2_model, "enable_attention_supervision", False ), ) global_visual_attn_maps = getattr( qwen2_model, "last_visual_attn_maps", None ) if global_visual_attn_maps is not None: batch_visual_attn_maps.append(global_visual_attn_maps) global_features = self.projector(global_features_2) global_features = global_features.reshape(-1, global_features.size(-1)) global_local_features = torch.cat( [global_features, self.view_seperator[None, :]], dim=0 )
image_slot_mask = images_seq_mask[idx].bool().to(inputs_embeds.device) num_slots = int(image_slot_mask.sum().item()) num_features = int(global_local_features.size(0)) if num_slots != num_features: raise ValueError( "ScanFlow Pro V2 image-token count mismatch for sample " f"{idx}: template reserved {num_slots} <image> positions, " f"but the visual encoder produced {num_features} features. " "The template must reserve (N_visual + T) slots per encoded " "view plus the existing view-separator slot." )
inputs_embeds[idx].masked_scatter_( image_slot_mask.unsqueeze(-1), global_local_features.to( device=inputs_embeds.device, dtype=inputs_embeds.dtype, ), ) idx += 1
self.last_visual_attn_maps = ( torch.cat(batch_visual_attn_maps, dim=0) if batch_visual_attn_maps else None )
return super(DeepseekOCR2Model, self).forward( input_ids=None, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, )
class DeepseekOCR2ForCausalLM(DeepseekV2ForCausalLM):
config_class = DeepseekOCR2Config # supports_gradient_checkpointing = True
def __init__(self, config): super(DeepseekV2ForCausalLM, self).__init__(config) self.model = DeepseekOCR2Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing self.post_init()
# Cross-forward snapshots reveal whether an optimizer step changed the # selected ScanFlow parameters. During gradient accumulation many # forwards will correctly report no change; a change should appear on # the first forward after optimizer.step(). self._scanflow_parameter_snapshot = {} self._scanflow_snapshot_forward_step = 0 self._scanflow_optimizer_membership_logged = False
def get_model(self): return self.model
def _scanflow_selected_named_parameters(self): patterns = scanflow_diagnostic_patterns() return [ (name, parameter) for name, parameter in self.named_parameters() if parameter.requires_grad and any(pattern in name for pattern in patterns) ]
def _scanflow_log_parameter_changes(self) -> None: if not self.training or not scanflow_is_main_process(): return if os.getenv("DEEPSEEK_OCR2_LOG_PARAMETER_UPDATES", "1") != "1": return
self._scanflow_snapshot_forward_step += 1 interval = max( 1, int(os.getenv("DEEPSEEK_OCR2_UPDATE_LOG_INTERVAL", "10")) ) selected = self._scanflow_selected_named_parameters()
# Compare current values with values saved at the end of the preceding # forward. A nonzero delta means an optimizer update occurred between # the two forwards. Zero deltas are expected during accumulation. if self._scanflow_parameter_snapshot and ( self._scanflow_snapshot_forward_step % interval == 0 ): changed_tensors = 0 total_update_sq = 0.0 total_parameter_sq = 0.0
for name, parameter in selected: previous = self._scanflow_parameter_snapshot.get(name) if previous is None: continue current = parameter.detach().float() delta = current - previous.to(device=current.device) update_norm = delta.norm().item() parameter_norm = current.norm().item() relative_update = update_norm / (parameter_norm + 1e-12) changed = update_norm > 0.0 changed_tensors += int(changed) total_update_sq += update_norm * update_norm total_parameter_sq += parameter_norm * parameter_norm
print( "[scanflow parameter update] " f"forward_step={self._scanflow_snapshot_forward_step} " f"name={name} " f"parameter_norm={parameter_norm:.8g} " f"update_norm={update_norm:.8g} " f"max_update={delta.abs().max().item():.8g} " f"relative_update={relative_update:.8g} " f"changed={changed} " f"finite={bool(torch.isfinite(delta).all().item())}", flush=True, )
total_update_norm = total_update_sq ** 0.5 total_parameter_norm = total_parameter_sq ** 0.5 print( "[scanflow parameter update summary] " f"forward_step={self._scanflow_snapshot_forward_step} " f"selected_tensors={len(selected)} " f"changed_tensors={changed_tensors} " f"total_update_norm={total_update_norm:.8g} " f"total_parameter_norm={total_parameter_norm:.8g} " f"relative_update={total_update_norm / (total_parameter_norm + 1e-12):.8g}", flush=True, )
def _scanflow_save_parameter_snapshot(self) -> None: if not self.training: return if os.getenv("DEEPSEEK_OCR2_LOG_PARAMETER_UPDATES", "1") != "1": return self._scanflow_parameter_snapshot = { name: parameter.detach().float().cpu().clone() for name, parameter in self._scanflow_selected_named_parameters() }
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, images: Optional[torch.FloatTensor] = None, images_seq_mask: Optional[torch.FloatTensor] = None, images_spatial_crop: Optional[torch.FloatTensor] = None, scanpath_lengths: Optional[torch.Tensor] = None, scanpath_steps: Optional[int] = None, fixation_targets: Optional[torch.Tensor] = None, fixation_mask: Optional[torch.Tensor] = None, fixation_loss_weight: Optional[float] = None, diversity_loss_weight: Optional[float] = None, attention_loss_weight: Optional[float] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
self._scanflow_log_parameter_changes()
requested_attention_weight = attention_loss_weight if requested_attention_weight is None: requested_attention_weight = float( os.getenv("DEEPSEEK_OCR2_ATTENTION_LOSS_WEIGHT", "0.0") ) requested_attention_weight = float(requested_attention_weight)
# Enable recurrent Qwen self-attention collection whenever the attention # objective or explicit attention-supervision switch is active. collect_attention_maps = ( requested_attention_weight != 0.0 or os.getenv("DEEPSEEK_OCR2_ENABLE_ATTENTION_SUPERVISION", "0") == "1" ) qwen_for_attention = getattr(self.model, "qwen2_model", None) if collect_attention_maps and qwen_for_attention is not None and hasattr( qwen_for_attention, "enable_attention_supervision" ): qwen_for_attention.enable_attention_supervision = True
outputs = self.model( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, position_ids=position_ids, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, images=images, images_seq_mask = images_seq_mask, images_spatial_crop = images_spatial_crop, labels=labels, return_dict=return_dict, scanpath_lengths=scanpath_lengths, scanpath_steps=scanpath_steps, )
# print(transformer_outputs)
hidden_states = outputs[0]
if not getattr(self, "_scanflow_printed_tensor_stats", False): scanflow_debug_tensor("hidden_states_before_lm_head", hidden_states) scanflow_debug_tensor("labels", labels) if labels is not None: valid_labels = labels[..., 1:] != -100 print( "[scanflow debug] valid shifted labels:", int(valid_labels.sum().item()), "/", valid_labels.numel(), flush=True, )
logits = self.lm_head(hidden_states) logits = logits.float()
if not getattr(self, "_scanflow_printed_tensor_stats", False): scanflow_debug_tensor("logits_after_lm_head", logits)
# logits
loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels)
lm_loss = loss # Recurrent Plan 1 deliberately supervises ONLY the Qwen self-attention # from each generated h_t to visual tokens. The old decoded-fixation and # fixation-diversity objectives are disabled by architecture, not merely # assigned small weights. fixation_loss = None diversity_loss = None attention_loss = None fixation_weight = 0.0 diversity_weight = 0.0 attention_weight = requested_attention_weight target_entropy = None prediction_entropy = None excess_fixation_ce = None attention_target_entropy = None attention_prediction_entropy = None attention_excess_ce = None
# Keep these legacy keyword arguments accepted so existing ms-swift data # plumbing does not break, but they have no effect in recurrent Plan 1. del fixation_loss_weight, diversity_loss_weight
if fixation_targets is not None and fixation_mask is not None: visual_attn_maps = getattr(self.model, "last_visual_attn_maps", None) if visual_attn_maps is None: qwen = getattr(self.model, "qwen2_model", None) visual_attn_maps = getattr(qwen, "last_visual_attn_maps", None)
needs_attention_maps = ( attention_weight != 0.0 or os.getenv("DEEPSEEK_OCR2_COMPUTE_ATTENTION_DIAGNOSTICS", "0") == "1" ) if visual_attn_maps is None and attention_weight != 0.0: raise RuntimeError( "DEEPSEEK_OCR2_ATTENTION_LOSS_WEIGHT is nonzero, but recurrent " "Plan 1 produced no Qwen self-attention maps. Ensure attention " "supervision is enabled before the recurrent encoder forward." )
if not getattr(self, "_scanflow_printed_tensor_stats", False): scanflow_debug_tensor("recurrent_plan1_visual_attn_maps", visual_attn_maps) scanflow_debug_tensor("fixation_targets", fixation_targets) scanflow_debug_tensor("fixation_mask", fixation_mask) self._scanflow_printed_tensor_stats = True
if visual_attn_maps is not None and needs_attention_maps: # deepencoderv2 retains only the four selected middle layers. # Within each layer the loss averages ALL 14 query heads, aligns # that layer-level map to the temporal fixation target, and then # averages the four independent layer losses. attention_loss = scanpath_attention_alignment_loss( visual_attn_maps=visual_attn_maps, fixation_targets=fixation_targets, fixation_mask=fixation_mask, ) ( attention_target_entropy, attention_prediction_entropy, attention_excess_ce, ) = scanpath_attention_entropy_metrics( visual_attn_maps=visual_attn_maps, fixation_targets=fixation_targets, fixation_mask=fixation_mask, )
if attention_loss is not None: attention_term = attention_weight * attention_loss loss = attention_term if lm_loss is None else lm_loss + attention_term
# Count forward micro-steps before optional diagnostics. self._scanflow_forward_step = getattr(self, "_scanflow_forward_step", 0) + 1
# Per-loss gradient diagnostics. torch.autograd.grad leaves .grad buffers # untouched, so the Trainer can still backpropagate the combined loss. # This is expensive, so logging is interval-controlled. self.last_gradient_metrics = None grad_logging_enabled = os.getenv("DEEPSEEK_OCR2_LOG_GRADIENTS", "1") == "1" grad_log_interval = max( 1, int(os.getenv("DEEPSEEK_OCR2_GRAD_LOG_INTERVAL", "10")) ) should_log_gradients = ( self.training and torch.is_grad_enabled() and grad_logging_enabled and self._scanflow_forward_step % grad_log_interval == 0 )
if should_log_gradients: filter_text = os.getenv("DEEPSEEK_OCR2_GRAD_PARAM_FILTER", "").strip() filters = [item.strip() for item in filter_text.split(",") if item.strip()] selected_named_parameters = [ (name, parameter) for name, parameter in self.named_parameters() if parameter.requires_grad and (not filters or any(token in name for token in filters)) ] selected_parameters = [parameter for _, parameter in selected_named_parameters]
if selected_parameters: lm_gradients = scanflow_loss_gradients(lm_loss, selected_parameters) fixation_gradients = scanflow_loss_gradients( fixation_loss, selected_parameters ) diversity_gradients = scanflow_loss_gradients( diversity_loss, selected_parameters ) attention_gradients = scanflow_loss_gradients( attention_loss, selected_parameters )
lm_grad_norm = scanflow_gradient_norm(lm_gradients) fixation_grad_norm = scanflow_gradient_norm(fixation_gradients) diversity_grad_norm = scanflow_gradient_norm(diversity_gradients) attention_grad_norm = scanflow_gradient_norm(attention_gradients) weighted_fixation_grad_norm = abs(float(fixation_weight)) * fixation_grad_norm weighted_diversity_grad_norm = abs(float(diversity_weight)) * diversity_grad_norm weighted_attention_grad_norm = abs(float(attention_weight)) * attention_grad_norm combined_grad_norm = scanflow_weighted_combined_gradient_norm([ (1.0, lm_gradients), (float(fixation_weight), fixation_gradients), (float(diversity_weight), diversity_gradients), (float(attention_weight), attention_gradients), ])
lm_fixation_cosine = scanflow_gradient_cosine( lm_gradients, fixation_gradients ) lm_diversity_cosine = scanflow_gradient_cosine( lm_gradients, diversity_gradients ) fixation_diversity_cosine = scanflow_gradient_cosine( fixation_gradients, diversity_gradients ) lm_attention_cosine = scanflow_gradient_cosine( lm_gradients, attention_gradients ) fixation_attention_cosine = scanflow_gradient_cosine( fixation_gradients, attention_gradients ) diversity_attention_cosine = scanflow_gradient_cosine( diversity_gradients, attention_gradients )
def _grad_value(value): return float(value.detach().float().cpu().item())
self.last_gradient_metrics = { "num_trainable_tensors": len(selected_named_parameters), "num_trainable_elements": sum( parameter.numel() for _, parameter in selected_named_parameters ), "lm_grad_norm": _grad_value(lm_grad_norm), "fixation_grad_norm": _grad_value(fixation_grad_norm), "diversity_grad_norm": _grad_value(diversity_grad_norm), "attention_grad_norm": _grad_value(attention_grad_norm), "weighted_fixation_grad_norm": _grad_value(weighted_fixation_grad_norm), "weighted_diversity_grad_norm": _grad_value(weighted_diversity_grad_norm), "weighted_attention_grad_norm": _grad_value(weighted_attention_grad_norm), "combined_grad_norm": _grad_value(combined_grad_norm), "lm_fixation_grad_cosine": _grad_value(lm_fixation_cosine), "lm_diversity_grad_cosine": _grad_value(lm_diversity_cosine), "fixation_diversity_grad_cosine": _grad_value(fixation_diversity_cosine), "lm_attention_grad_cosine": _grad_value(lm_attention_cosine), "fixation_attention_grad_cosine": _grad_value(fixation_attention_cosine), "diversity_attention_grad_cosine": _grad_value(diversity_attention_cosine), }
print( "[scanflow gradients] " f"forward_step={self._scanflow_forward_step} " f"trainable_tensors={self.last_gradient_metrics['num_trainable_tensors']} " f"trainable_elements={self.last_gradient_metrics['num_trainable_elements']} " f"lm_norm={self.last_gradient_metrics['lm_grad_norm']:.6g} " f"fixation_norm={self.last_gradient_metrics['fixation_grad_norm']:.6g} " f"diversity_norm={self.last_gradient_metrics['diversity_grad_norm']:.6g} " f"attention_norm={self.last_gradient_metrics['attention_grad_norm']:.6g} " f"weighted_fixation_norm={self.last_gradient_metrics['weighted_fixation_grad_norm']:.6g} " f"weighted_diversity_norm={self.last_gradient_metrics['weighted_diversity_grad_norm']:.6g} " f"weighted_attention_norm={self.last_gradient_metrics['weighted_attention_grad_norm']:.6g} " f"combined_norm={self.last_gradient_metrics['combined_grad_norm']:.6g} " f"cos_lm_fixation={self.last_gradient_metrics['lm_fixation_grad_cosine']:.6g} " f"cos_lm_diversity={self.last_gradient_metrics['lm_diversity_grad_cosine']:.6g} " f"cos_fixation_diversity={self.last_gradient_metrics['fixation_diversity_grad_cosine']:.6g} " f"cos_lm_attention={self.last_gradient_metrics['lm_attention_grad_cosine']:.6g} " f"cos_fixation_attention={self.last_gradient_metrics['fixation_attention_grad_cosine']:.6g} " f"cos_diversity_attention={self.last_gradient_metrics['diversity_attention_grad_cosine']:.6g}", flush=True, )
if os.getenv("DEEPSEEK_OCR2_LOG_NAMED_GRADIENTS", "1") == "1": named_limit = max( 1, int(os.getenv("DEEPSEEK_OCR2_NAMED_GRADIENT_LIMIT", "80")), ) for parameter_index, ( parameter_name, parameter, ) in enumerate(selected_named_parameters[:named_limit]): lm_grad = lm_gradients[parameter_index] fix_grad = fixation_gradients[parameter_index] div_grad = diversity_gradients[parameter_index] attn_grad = attention_gradients[parameter_index]
def _named_norm(grad): if grad is None: return None return grad.detach().float().norm().item()
def _named_max(grad): if grad is None: return None return grad.detach().float().abs().max().item()
fix_norm = _named_norm(fix_grad) attn_norm = _named_norm(attn_grad) weighted_fix_norm = ( None if fix_norm is None else abs(float(fixation_weight)) * fix_norm ) weighted_attn_norm = ( None if attn_norm is None else abs(float(attention_weight)) * attn_norm )
print( "[scanflow named component gradient] " f"forward_step={self._scanflow_forward_step} " f"name={parameter_name} " f"shape={tuple(parameter.shape)} " f"parameter_norm={parameter.detach().float().norm().item():.8g} " f"lm_norm={_named_norm(lm_grad)} " f"fixation_norm={fix_norm} " f"weighted_fixation_norm={weighted_fix_norm} " f"diversity_norm={_named_norm(div_grad)} " f"attention_norm={attn_norm} " f"weighted_attention_norm={weighted_attn_norm} " f"fixation_max={_named_max(fix_grad)} " f"attention_max={_named_max(attn_grad)} " f"fixation_grad_none={fix_grad is None} " f"attention_grad_none={attn_grad is None}", flush=True, )
self.last_lm_loss = lm_loss.detach() if lm_loss is not None else None self.last_fixation_loss = fixation_loss.detach() if fixation_loss is not None else None self.last_diversity_loss = diversity_loss.detach() if diversity_loss is not None else None self.last_attention_loss = attention_loss.detach() if attention_loss is not None else None self.last_target_entropy = target_entropy.detach() if target_entropy is not None else None self.last_prediction_entropy = prediction_entropy.detach() if prediction_entropy is not None else None self.last_excess_fixation_ce = excess_fixation_ce.detach() if excess_fixation_ce is not None else None self.last_attention_target_entropy = attention_target_entropy.detach() if attention_target_entropy is not None else None self.last_attention_prediction_entropy = attention_prediction_entropy.detach() if attention_prediction_entropy is not None else None self.last_attention_excess_ce = attention_excess_ce.detach() if attention_excess_ce is not None else None
if os.getenv("DEEPSEEK_OCR2_LOG_LOSSES", "1") == "1": def _loss_value(value): if value is None: return None return float(value.detach().float().item())
print( "[scanflow losses] " f"forward_step={self._scanflow_forward_step} " f"total={_loss_value(loss)} " f"lm={_loss_value(lm_loss)} " f"fixation={_loss_value(fixation_loss)} " f"target_entropy={_loss_value(target_entropy)} " f"prediction_entropy={_loss_value(prediction_entropy)} " f"excess_fixation_ce={_loss_value(excess_fixation_ce)} " f"diversity={_loss_value(diversity_loss)} " f"attention={_loss_value(attention_loss)} " f"attention_target_entropy={_loss_value(attention_target_entropy)} " f"attention_prediction_entropy={_loss_value(attention_prediction_entropy)} " f"attention_excess_ce={_loss_value(attention_excess_ce)} " f"fixation_weight={float(fixation_weight):.6g} " f"diversity_weight={float(diversity_weight):.6g} " f"attention_weight={float(attention_weight):.6g}", flush=True, )
self._scanflow_save_parameter_snapshot()
if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs ): # Omit tokens covered by past_key_values past_length = 0 if past_key_values is not None: if isinstance(past_key_values, Cache): cache_length = past_key_values.get_seq_length() past_length = past_key_values.seen_tokens max_cache_length = past_key_values.get_max_length() else: cache_length = past_length = past_key_values[0][0].shape[2] max_cache_length = None
# Keep only the unprocessed tokens: # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as # input) if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard # input_ids based on the past_length. elif past_length < input_ids.shape[1]: input_ids = input_ids[:, past_length:] # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask. if ( max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length ): attention_mask = attention_mask[:, -max_cache_length:]
position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -input_ids.shape[1] :]
# if self.generation_config.cache_implementation == "static": # # generation with static cache # cache_position = kwargs.get("cache_position", None) # if cache_position is None: # past_length = 0 # else: # past_length = cache_position[-1] + 1 # input_ids = input_ids[:, past_length:] # position_ids = position_ids[:, past_length:]
# TODO @gante we should only keep a `cache_position` in generate, and do +=1. # same goes for position ids. Could also help with continued generation. cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids}
model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, "images": kwargs.get("images", None), "images_seq_mask": kwargs.get("images_seq_mask", None), "images_spatial_crop": kwargs.get("images_spatial_crop", None), "scanpath_lengths": kwargs.get("scanpath_lengths", None), "scanpath_steps": kwargs.get("scanpath_steps", None), } ) return model_inputs
def disable_torch_init(self): """ Disable the redundant torch default initialization to accelerate model creation. """ import torch setattr(torch.nn.Linear, "reset_parameters", lambda self: None) setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
def infer(self, tokenizer, prompt='', image_file='', output_path = '', base_size=1024, image_size=640, crop_mode=True, test_compress=False, save_results=False, eval_mode=False, scanpath_steps=32): self.disable_torch_init()
os.makedirs(output_path, exist_ok=True) os.makedirs(f'{output_path}/images', exist_ok=True)
if prompt and image_file: conversation = [ { "role": "<|User|>", # "content": "<image>\n<|grounding|>Given the layout of the image. ", "content": f'{prompt}', # "content": "君不见黄河之水天上来的下一句是什么?", # "content": "<image>\nFree OCR. ", # "content": "<image>\nParse the figure. ", # "content": "<image>\nExtract the text in the image. ", "images": [f'{image_file}'], }, {"role": "<|Assistant|>", "content": ""}, ] elif prompt: conversation = [ { "role": "<|User|>", # "content": "<image>\n<|grounding|>Given the layout of the image. ", "content": f'{prompt}', # "content": "君不见黄河之水天上来的下一句是什么?", # "content": "<image>\nFree OCR. ", # "content": "<image>\nParse the figure. ", # "content": "<image>\nExtract the text in the image. ", # "images": [f'{image_file}'], }, {"role": "<|Assistant|>", "content": ""}, ] else: assert False, f'prompt is none!' prompt = format_messages(conversations=conversation, sft_format='plain', system_prompt='')
patch_size = 16 downsample_ratio = 4 images = load_pil_images(conversation)
valid_img_tokens = 0 ratio = 1
image_draw = images[0].copy()
w,h = image_draw.size # print(w, h) ratio = 1 - ((max(w, h) - min(w, h)) / (max(w, h)))
image_transform=BasicImageTransform(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), normalize=True) images_seq_mask = []
image_token = '<image>' image_token_id = 128815 text_splits = prompt.split(image_token)
images_list, images_crop_list, images_seq_mask = [], [], [] tokenized_str = [] images_spatial_crop = [] for text_sep, image in zip(text_splits, images):
tokenized_sep = text_encode(tokenizer, text_sep, bos=False, eos=False) tokenized_str += tokenized_sep images_seq_mask += [False] * len(tokenized_sep)
if crop_mode:
if image.size[0] <= 768 and image.size[1] <= 768: crop_ratio = [1, 1]
else: if crop_mode: # best_width, best_height = select_best_resolution(image.size, self.candidate_resolutions) images_crop_raw, crop_ratio = dynamic_preprocess(image) else: # best_width, best_height = self.image_size, self.image_size crop_ratio = [1, 1] """process the global view""" # image = image.resize((base_size, base_size)) global_view = ImageOps.pad(image, (base_size, base_size), color=tuple(int(x * 255) for x in image_transform.mean)) if base_size == 1024: valid_img_tokens += int(256 * ratio) elif base_size == 1280: valid_img_tokens += int(400 * ratio) # elif base_size == 640: # valid_img_tokens += int(100 * ratio)
images_list.append(image_transform(global_view).to(torch.bfloat16))
# global_view_tensor = image_transform(global_view).to(torch.bfloat16)
width_crop_num, height_crop_num = crop_ratio
images_spatial_crop.append([width_crop_num, height_crop_num]) if width_crop_num > 1 or height_crop_num > 1: """process the local views""" for i in range(len(images_crop_raw)): images_crop_list.append(image_transform(images_crop_raw[i]).to(torch.bfloat16)) if image_size == 768: valid_img_tokens += len(images_crop_list) * 144
num_queries = math.ceil((image_size // patch_size) / downsample_ratio) num_queries_base = math.ceil((base_size // patch_size) / downsample_ratio)
"""add image tokens"""
# ScanFlow Pro V2 returns [V + lambda(V,Q)*R; H] for the global view # and every local crop: N_visual residual-modified visual tokens # plus T recurrent reasoning states per view. num_local_views = ( width_crop_num * height_crop_num if (width_crop_num > 1 or height_crop_num > 1) else 0 ) global_v2_tokens = num_queries_base ** 2 + int(scanpath_steps) local_v2_tokens = num_queries ** 2 + int(scanpath_steps) num_scanflow_v2_image_tokens = ( global_v2_tokens + num_local_views * local_v2_tokens + 1 ) # +1 existing view separator tokenized_image = [image_token_id] * num_scanflow_v2_image_tokens tokenized_str += tokenized_image images_seq_mask += [True] * len(tokenized_image) # num_image_tokens.append(len(tokenized_image))
else: # best_width, best_height = self.image_size, self.image_size # print(image.size, (best_width, best_height)) # check the select_best_resolutions func
"""process the global view""" if image_size <= 768: print('directly resize') image = image.resize((image_size, image_size)) # else: global_view = ImageOps.pad(image, (image_size, image_size), color=tuple(int(x * 255) for x in image_transform.mean)) images_list.append(image_transform(global_view).to(torch.bfloat16))
if base_size == 1024: valid_img_tokens += int(256 * ratio) elif base_size == 1280: valid_img_tokens += int(400 * ratio) elif base_size == 640: valid_img_tokens += int(100 * 1) elif base_size == 512: valid_img_tokens += int(64 * 1) elif base_size == 768: valid_img_tokens += int(144 * 1)
width_crop_num, height_crop_num = 1, 1
images_spatial_crop.append([width_crop_num, height_crop_num])
"""add image tokens""" num_queries = math.ceil((image_size // patch_size) / downsample_ratio)
# ScanFlow Pro V2: [V + lambda(V,Q)*R; H] for one global view, # plus the existing separator. tokenized_image = [image_token_id] * ( num_queries ** 2 + int(scanpath_steps) + 1 ) # tokenized_image += ([self.image_token_id] * (num_queries * width_crop_num) + [self.image_token_id]) * ( # num_queries * height_crop_num) tokenized_str += tokenized_image images_seq_mask += [True] * len(tokenized_image) # num_image_tokens.append(len(tokenized_image))
"""process the last text split""" tokenized_sep = text_encode(tokenizer, text_splits[-1], bos=False, eos=False) tokenized_str += tokenized_sep images_seq_mask += [False] * len(tokenized_sep)
"""add the bos tokens""" bos_id = 0 tokenized_str = [bos_id] + tokenized_str images_seq_mask = [False] + images_seq_mask
input_ids = torch.LongTensor(tokenized_str)
images_seq_mask = torch.tensor(images_seq_mask, dtype=torch.bool)
if len(images_list) == 0: images_ori = torch.zeros((1, 3, image_size, image_size)) images_spatial_crop = torch.zeros((1, 2), dtype=torch.long) images_crop = torch.zeros((1, 3, base_size, base_size))
else: images_ori = torch.stack(images_list, dim=0) images_spatial_crop = torch.tensor(images_spatial_crop, dtype=torch.long) if images_crop_list: images_crop = torch.stack(images_crop_list, dim=0) else: images_crop = torch.zeros((1, 3, base_size, base_size))
if not eval_mode: streamer = NoEOSTextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False) with torch.autocast("cuda", dtype=torch.bfloat16): with torch.no_grad(): output_ids = self.generate( input_ids.unsqueeze(0).cuda(), images=[(images_crop.cuda(), images_ori.cuda())], images_seq_mask = images_seq_mask.unsqueeze(0).cuda(), images_spatial_crop = images_spatial_crop, scanpath_steps = int(scanpath_steps), # do_sample=False, # num_beams = 1, temperature=0.0, eos_token_id=tokenizer.eos_token_id, streamer=streamer, max_new_tokens=8192, no_repeat_ngram_size = 20, use_cache = True )
else: with torch.autocast("cuda", dtype=torch.bfloat16): with torch.no_grad(): output_ids = self.generate( input_ids.unsqueeze(0).cuda(), images=[(images_crop.cuda(), images_ori.cuda())], images_seq_mask = images_seq_mask.unsqueeze(0).cuda(), images_spatial_crop = images_spatial_crop, scanpath_steps = int(scanpath_steps), # do_sample=False, # num_beams = 1, temperature=0.0, eos_token_id=tokenizer.eos_token_id, max_new_tokens=8192, no_repeat_ngram_size = 35, use_cache = True )
if '<image>' in conversation[0]['content'] and eval_mode: outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:]) stop_str = '<|end▁of▁sentence|>' if outputs.endswith(stop_str): outputs = outputs[:-len(stop_str)] # re_match outputs = outputs.strip()
return outputs if '<image>' in conversation[0]['content'] and test_compress: outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:]) pure_texts_outputs_token_length = len(text_encode(tokenizer, outputs, bos=False, eos=False)) print('='*50) print('image size: ', (w, h)) print('valid image tokens: ', int(valid_img_tokens)) print('output texts tokens (valid): ', pure_texts_outputs_token_length) print('compression ratio: ', round(pure_texts_outputs_token_length/valid_img_tokens, 2)) print('='*50)
if '<image>' in conversation[0]['content'] and save_results: outputs = tokenizer.decode(output_ids[0, input_ids.unsqueeze(0).cuda().shape[1]:]) stop_str = '<|end▁of▁sentence|>'
print('='*15 + 'save results:' + '='*15) # # # # conv.messages[-1][-1] = outputs if outputs.endswith(stop_str): outputs = outputs[:-len(stop_str)] outputs = outputs.strip()
matches_ref, matches_images, mathes_other = re_match(outputs) # print(matches_ref) result = process_image_with_refs(image_draw, matches_ref, output_path)
for idx, a_match_image in enumerate(tqdm(matches_images, desc="image")): outputs = outputs.replace(a_match_image, ' + '.jpg)\n') for idx, a_match_other in enumerate(tqdm(mathes_other, desc="other")): outputs = outputs.replace(a_match_other, '').replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
# if 'structural formula' in conversation[0]['content']: # outputs = '<smiles>' + outputs + '</smiles>' with open(f'{output_path}/result.mmd', 'w', encoding = 'utf-8') as afile: afile.write(outputs)
if 'line_type' in outputs: import matplotlib.pyplot as plt lines = eval(outputs)['Line']['line']
line_type = eval(outputs)['Line']['line_type'] # print(lines)
endpoints = eval(outputs)['Line']['line_endpoint']
fig, ax = plt.subplots(figsize=(3,3), dpi=200) ax.set_xlim(-15, 15) ax.set_ylim(-15, 15)
for idx, line in enumerate(lines): try: p0 = eval(line.split(' -- ')[0]) p1 = eval(line.split(' -- ')[-1])
if line_type[idx] == '--': ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth=0.8, color='k') else: ax.plot([p0[0], p1[0]], [p0[1], p1[1]], linewidth = 0.8, color = 'k')
ax.scatter(p0[0], p0[1], s=5, color = 'k') ax.scatter(p1[0], p1[1], s=5, color = 'k') except: pass
for endpoint in endpoints:
label = endpoint.split(': ')[0] (x, y) = eval(endpoint.split(': ')[1]) ax.annotate(label, (x, y), xytext=(1, 1), textcoords='offset points', fontsize=5, fontweight='light')
plt.savefig(f'{output_path}/geo.jpg') plt.close()
result.save(f"{output_path}/result_with_boxes.jpg")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998# coding=utf-8# Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.## This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX# and OPT implementations in this library. It has been modified from its# original forms to accommodate minor architectural differences compared# to GPT-NeoX and OPT used by the Meta AI team that trained the model.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.""" PyTorch DeepSeek model and compatible with both DeepSeekV2 and DeepSeekV3"""import mathimport warningsfrom typing import List, Optional, Tuple, Unionimport numpy as np
import torchimport torch.nn.functional as Fimport torch.utils.checkpointimport torch.distributed as distfrom einops import repeatfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_maskfrom transformers.models.llama.modeling_llama import ( LlamaAttention # LlamaFlashAttention2)
try: from transformers.models.llama.modeling_llama import LlamaFlashAttention2except ImportError: LlamaFlashAttention2 = LlamaAttention
from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.pytorch_utils import ( ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13,)from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings,)from transformers.utils.import_utils import is_torch_fx_available
from .configuration_deepseek_v2 import DeepseekV2Config
if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.# It means that the function will not be traced through and simply appear as a node in the graph.if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "DeepseekV2Config"
def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad( torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0) ) return ( indices, cu_seqlens, max_seqlen_in_batch, )
class DeepseekV2RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ DeepseekV2RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
ALL_LAYERNORM_LAYERS.append(DeepseekV2RMSNorm)
class DeepseekV2RotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__()
self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / ( self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False)
# Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(), ) self.max_seq_len_cached = None
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype )
freqs = torch.outer(t, self.inv_freq.to(t.device)) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), )
# Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV2class DeepseekV2LinearScalingRotaryEmbedding(DeepseekV2RotaryEmbedding): """DeepseekV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) t = t / self.scaling_factor
freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
# Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV2class DeepseekV2DynamicNTKScalingRotaryEmbedding(DeepseekV2RotaryEmbedding): """DeepseekV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len
if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / ( base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype )
freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
# Inverse dim formula to find dim based on number of rotationsdef yarn_find_correction_dim( num_rotations, dim, base=10000, max_position_embeddings=2048): return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / ( 2 * math.log(base) )
# Find dim range bounds based on rotationsdef yarn_find_correction_range( low_rot, high_rot, dim, base=10000, max_position_embeddings=2048): low = math.floor( yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings) ) high = math.ceil( yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings) ) return max(low, 0), min(high, dim - 1) # Clamp values just in case
def yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0
def yarn_linear_ramp_mask(min, max, dim): if min == max: max += 0.001 # Prevent singularity
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) ramp_func = torch.clamp(linear_func, 0, 1) return ramp_func
class DeepseekV2YarnRotaryEmbedding(DeepseekV2RotaryEmbedding):
def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, original_max_position_embeddings=4096, beta_fast=32, beta_slow=1, mscale=1, mscale_all_dim=0, ): self.scaling_factor = scaling_factor self.original_max_position_embeddings = original_max_position_embeddings self.beta_fast = beta_fast self.beta_slow = beta_slow self.mscale = mscale self.mscale_all_dim = mscale_all_dim super().__init__(dim, max_position_embeddings, base, device)
def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len dim = self.dim
freq_extra = 1.0 / ( self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) ) freq_inter = 1.0 / ( self.scaling_factor * self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) )
low, high = yarn_find_correction_range( self.beta_fast, self.beta_slow, dim, self.base, self.original_max_position_embeddings, ) inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to( device=device, dtype=torch.float32 ) inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(seq_len, device=device, dtype=torch.float32)
freqs = torch.outer(t, inv_freq)
_mscale = float( yarn_get_mscale(self.scaling_factor, self.mscale) / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim) )
emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer( "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False ) self.register_buffer( "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False )
# Copied from transformers.models.llama.modeling_llama.rotate_halfdef rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_embdef apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.
Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos[position_ids].unsqueeze(unsqueeze_dim) sin = sin[position_ids].unsqueeze(unsqueeze_dim)
# print()
b, h, s, d = q.shape q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
class DeepseekV2MLP(nn.Module): def __init__(self, config, hidden_size=None, intermediate_size=None): super().__init__() self.config = config self.hidden_size = config.hidden_size if hidden_size is None else hidden_size self.intermediate_size = ( config.intermediate_size if intermediate_size is None else intermediate_size )
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj
class MoEGate(nn.Module): def __init__(self, config): super().__init__() self.config = config self.top_k = config.num_experts_per_tok self.n_routed_experts = config.n_routed_experts self.routed_scaling_factor = config.routed_scaling_factor self.scoring_func = config.scoring_func self.alpha = config.aux_loss_alpha self.seq_aux = config.seq_aux self.topk_method = config.topk_method self.n_group = config.n_group self.topk_group = config.topk_group
# topk selection algorithm self.norm_topk_prob = config.norm_topk_prob self.gating_dim = config.hidden_size self.weight = nn.Parameter( torch.empty((self.n_routed_experts, self.gating_dim)) ) if self.topk_method == "noaux_tc": self.e_score_correction_bias = nn.Parameter( torch.empty((self.n_routed_experts)) ) self.reset_parameters()
def reset_parameters(self) -> None: import torch.nn.init as init
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
def forward(self, hidden_states): bsz, seq_len, h = hidden_states.shape ### compute gating score hidden_states = hidden_states.view(-1, h) logits = F.linear( hidden_states.type(torch.float32), self.weight.type(torch.float32), None ) if self.scoring_func == "softmax": scores = logits.softmax(dim=-1, dtype=torch.float32) elif self.scoring_func == "sigmoid": scores = logits.sigmoid() else: raise NotImplementedError( f"insupportable scoring function for MoE gating: {self.scoring_func}" )
### select top-k experts if self.topk_method == "greedy": topk_weight, topk_idx = torch.topk( scores, k=self.top_k, dim=-1, sorted=False ) elif self.topk_method == "group_limited_greedy": group_scores = ( scores.view(bsz * seq_len, self.n_group, -1).max(dim=-1).values ) # [n, n_group] group_idx = torch.topk( group_scores, k=self.topk_group, dim=-1, sorted=False )[ 1 ] # [n, top_k_group] group_mask = torch.zeros_like(group_scores) # [n, n_group] group_mask.scatter_(1, group_idx, 1) # [n, n_group] score_mask = ( group_mask.unsqueeze(-1) .expand( bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group ) .reshape(bsz * seq_len, -1) ) # [n, e] tmp_scores = scores.masked_fill(~score_mask.bool(), 0.0) # [n, e] topk_weight, topk_idx = torch.topk( tmp_scores, k=self.top_k, dim=-1, sorted=False ) elif self.topk_method == "noaux_tc": assert not self.training scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0) group_scores = ( scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1) ) # [n, n_group] group_idx = torch.topk( group_scores, k=self.topk_group, dim=-1, sorted=False )[ 1 ] # [n, top_k_group] group_mask = torch.zeros_like(group_scores) # [n, n_group] group_mask.scatter_(1, group_idx, 1) # [n, n_group] score_mask = ( group_mask.unsqueeze(-1) .expand( bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group ) .reshape(bsz * seq_len, -1) ) # [n, e] tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e] _, topk_idx = torch.topk( tmp_scores, k=self.top_k, dim=-1, sorted=False ) topk_weight = scores.gather(1, topk_idx)
### norm gate to sum 1 if self.top_k > 1 and self.norm_topk_prob: denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20 topk_weight = topk_weight / denominator * self.routed_scaling_factor else: topk_weight = topk_weight * self.routed_scaling_factor ### expert-level computation auxiliary loss if self.training and self.alpha > 0.0: scores_for_aux = scores aux_topk = self.top_k # always compute aux loss based on the naive greedy topk method topk_idx_for_aux_loss = topk_idx.view(bsz, -1) if self.seq_aux: scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1) ce = torch.zeros( bsz, self.n_routed_experts, device=hidden_states.device ) ce.scatter_add_( 1, topk_idx_for_aux_loss, torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device), ).div_(seq_len * aux_topk / self.n_routed_experts) aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum( dim=1 ).mean() * self.alpha else: mask_ce = F.one_hot( topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts ) ce = mask_ce.float().mean(0) Pi = scores_for_aux.mean(0) fi = ce * self.n_routed_experts aux_loss = (Pi * fi).sum() * self.alpha else: aux_loss = None return topk_idx, topk_weight, aux_loss
class AddAuxiliaryLoss(torch.autograd.Function): """ The trick function of adding auxiliary (aux) loss, which includes the gradient of the aux loss during backpropagation. """
@staticmethod def forward(ctx, x, loss): assert loss.numel() == 1 ctx.dtype = loss.dtype ctx.required_aux_loss = loss.requires_grad return x
@staticmethod def backward(ctx, grad_output): grad_loss = None if ctx.required_aux_loss: grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device) return grad_output, grad_loss
class DeepseekV2MoE(nn.Module): """ A mixed expert module containing shared experts. """
def __init__(self, config): super().__init__() self.config = config self.num_experts_per_tok = config.num_experts_per_tok
if hasattr(config, "ep_size") and config.ep_size > 1: assert config.ep_size == dist.get_world_size() self.ep_size = config.ep_size self.experts_per_rank = config.n_routed_experts // config.ep_size self.ep_rank = dist.get_rank() self.experts = nn.ModuleList( [ ( DeepseekV2MLP( config, intermediate_size=config.moe_intermediate_size ) if i >= self.ep_rank * self.experts_per_rank and i < (self.ep_rank + 1) * self.experts_per_rank else None ) for i in range(config.n_routed_experts) ] ) else: self.ep_size = 1 self.experts_per_rank = config.n_routed_experts self.ep_rank = 0 self.experts = nn.ModuleList( [ DeepseekV2MLP( config, intermediate_size=config.moe_intermediate_size ) for i in range(config.n_routed_experts) ] ) self.gate = MoEGate(config) if config.n_shared_experts is not None: intermediate_size = config.moe_intermediate_size * config.n_shared_experts self.shared_experts = DeepseekV2MLP( config=config, intermediate_size=intermediate_size )
def forward(self, hidden_states): identity = hidden_states orig_shape = hidden_states.shape topk_idx, topk_weight, aux_loss = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) flat_topk_idx = topk_idx.view(-1) if self.training: hidden_states = hidden_states.repeat_interleave( self.num_experts_per_tok, dim=0 ) y = torch.empty_like(hidden_states) for i, expert in enumerate(self.experts): y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i]) y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1) y = y.to(hidden_states.dtype).view(*orig_shape) y = AddAuxiliaryLoss.apply(y, aux_loss) else: y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape) if self.config.n_shared_experts is not None: y = y + self.shared_experts(identity) return y
@torch.no_grad() def moe_infer(self, x, topk_ids, topk_weight): cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) idxs = topk_ids.view(-1).argsort() sorted_tokens = x[idxs // topk_ids.shape[1]] sorted_tokens_shape = sorted_tokens.shape if self.ep_size > 1: tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1) tokens_per_expert_group = tokens_per_expert.new_empty( tokens_per_expert.shape[0] ) dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert) output_splits = ( tokens_per_expert_group.view(self.ep_size, -1) .sum(1) .cpu() .numpy() .tolist() ) gathered_tokens = sorted_tokens.new_empty( tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1] ) input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist() dist.all_to_all( list(gathered_tokens.split(output_splits)), list(sorted_tokens.split(input_split_sizes)), ) tokens_per_expert_post_gather = tokens_per_expert_group.view( self.ep_size, self.experts_per_rank ).sum(dim=0) gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32) s = 0 for i, k in enumerate(tokens_per_expert_group.cpu().numpy()): gatherd_idxs[s : s + k] = i % self.experts_per_rank s += k gatherd_idxs = gatherd_idxs.argsort() sorted_tokens = gathered_tokens[gatherd_idxs] tokens_per_expert = tokens_per_expert_post_gather tokens_per_expert = tokens_per_expert.cpu().numpy()
outputs = [] start_idx = 0 for i, num_tokens in enumerate(tokens_per_expert): end_idx = start_idx + num_tokens if num_tokens == 0: continue expert = self.experts[i + self.ep_rank * self.experts_per_rank] tokens_for_this_expert = sorted_tokens[start_idx:end_idx] expert_out = expert(tokens_for_this_expert) outputs.append(expert_out) start_idx = end_idx
outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0) if self.ep_size > 1: new_x = torch.empty_like(outs) new_x[gatherd_idxs] = outs gathered_tokens = new_x.new_empty(*sorted_tokens_shape) dist.all_to_all( list(gathered_tokens.split(input_split_sizes)), list(new_x.split(output_splits)), ) outs = gathered_tokens
new_x = torch.empty_like(outs) new_x[idxs] = outs final_out = ( new_x.view(*topk_ids.shape, -1) .type(topk_weight.dtype) .mul_(topk_weight.unsqueeze(dim=-1)) .sum(dim=1) .type(new_x.dtype) ) return final_out
# Copied from transformers.models.llama.modeling_llama.repeat_kvdef repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim ) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV2class DeepseekV2Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: DeepseekV2Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." )
self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads
self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta self.q_lora_rank = config.q_lora_rank self.qk_rope_head_dim = config.qk_rope_head_dim self.kv_lora_rank = config.kv_lora_rank self.v_head_dim = config.v_head_dim self.qk_nope_head_dim = config.qk_nope_head_dim self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
self.is_causal = True
if self.q_lora_rank is None: self.q_proj = nn.Linear( self.hidden_size, self.num_heads * self.q_head_dim, bias=False ) else: self.q_a_proj = nn.Linear( self.hidden_size, config.q_lora_rank, bias=config.attention_bias ) self.q_a_layernorm = DeepseekV2RMSNorm(config.q_lora_rank) self.q_b_proj = nn.Linear( config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False ) # config.kv_lora_rank + config.qk_rope_head_dim, self.kv_a_proj_with_mqa = nn.Linear( self.hidden_size, config.kv_lora_rank + config.qk_rope_head_dim, bias=config.attention_bias, ) self.kv_a_layernorm = DeepseekV2RMSNorm(config.kv_lora_rank) self.kv_b_proj = nn.Linear( config.kv_lora_rank, self.num_heads * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim), bias=False, )
self.o_proj = nn.Linear( self.num_heads * self.v_head_dim, self.hidden_size, bias=config.attention_bias, ) self._init_rope()
self.softmax_scale = self.q_head_dim ** (-0.5) if self.config.rope_scaling is not None: mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0) scaling_factor = self.config.rope_scaling["factor"] if mscale_all_dim: mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) self.softmax_scale = self.softmax_scale * mscale * mscale
def _init_rope(self): if self.config.rope_scaling is None: self.rotary_emb = DeepseekV2RotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) # self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding( # self.qk_rope_head_dim, # max_position_embeddings=self.max_position_embeddings, # scaling_factor=scaling_factor, # base=self.rope_theta, # ) else: scaling_type = self.config.rope_scaling["type"] scaling_factor = self.config.rope_scaling["factor"] if scaling_type == "linear": self.rotary_emb = DeepseekV2LinearScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "dynamic": self.rotary_emb = DeepseekV2DynamicNTKScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "yarn": kwargs = { key: self.config.rope_scaling[key] for key in [ "original_max_position_embeddings", "beta_fast", "beta_slow", "mscale", "mscale_all_dim", ] if key in self.config.rope_scaling } self.rotary_emb = DeepseekV2YarnRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, **kwargs, ) else: raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return ( tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim) .transpose(1, 2) .contiguous() )
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) bsz, q_len, _ = hidden_states.size()
if self.q_lora_rank is None: q = self.q_proj(hidden_states) else: q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 )
compressed_kv = self.kv_a_proj_with_mqa(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) compressed_kv = self.kv_a_layernorm(compressed_kv) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
kv_seq_len = k_pe.shape[-2] if past_key_value is not None: if self.layer_idx is None: raise ValueError( f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " "with a layer index." ) kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
cos, sin = self.rotary_emb(q_pe, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models compressed_kv = compressed_kv.unsqueeze(1) k_pe, compressed_kv = past_key_value.update(k_pe, compressed_kv, self.layer_idx, cache_kwargs) compressed_kv = compressed_kv.squeeze(1)
kv_b_proj = self.kv_b_proj.weight.view(self.num_heads, -1, self.kv_lora_rank) q_absorb = kv_b_proj[:, :self.qk_nope_head_dim, :] out_absorb = kv_b_proj[:, self.qk_nope_head_dim:, :]
q_nope = torch.matmul(q_nope, q_absorb) attn_weights = (torch.matmul(q_pe, k_pe.mT) + torch.matmul(q_nope, compressed_kv.unsqueeze(-3).mT)) * self.softmax_scale if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): raise ValueError( f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" f" {attn_weights.size()}" ) assert attention_mask is not None if attention_mask is not None: if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask
# upcast attention to fp32 attn_weights = nn.functional.softmax( attn_weights, dim=-1, dtype=torch.float32 ).to(q_pe.dtype) attn_weights = nn.functional.dropout( attn_weights, p=self.attention_dropout, training=self.training ) attn_output = torch.einsum('bhql,blc->bhqc', attn_weights, compressed_kv)
attn_output = torch.matmul(attn_output, out_absorb.mT)
if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is" f" {attn_output.size()}" )
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
attn_output = self.o_proj(attn_output)
if not output_attentions: attn_weights = None
return attn_output, attn_weights, past_key_value
# Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV2class DeepseekV2FlashAttention2(DeepseekV2Attention): """ DeepseekV2 flash attention module. This module inherits from `DeepseekV2Attention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # DeepseekV2FlashAttention2 attention does not support output_attentions if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" )
# overwrite attention_mask with padding_mask attention_mask = kwargs.pop("padding_mask")
output_attentions = False
bsz, q_len, _ = hidden_states.size()
if self.q_lora_rank is None: q = self.q_proj(hidden_states) else: q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 )
# Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape compressed_kv = self.kv_a_proj_with_mqa(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.kv_b_proj(self.kv_a_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) )
k_nope, value_states = torch.split( kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 ) kv_seq_len = value_states.shape[-2]
kv_seq_len = value_states.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
if self.q_head_dim != self.v_head_dim: value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
# TODO: support compressed_kv for kv_cache (instead of key_states, value_states) in flash_attention version if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs )
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2)
dropout_rate = self.attention_dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (DeepseekV2RMSNorm handles it correctly)
input_dtype = query_states.dtype if input_dtype == torch.float32: # Handle the case where the model is quantized if hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype elif torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() else: target_dtype = ( self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype )
logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." )
query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype)
attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate, softmax_scale=self.softmax_scale, ) if self.q_head_dim != self.v_head_dim: attn_output = attn_output[:, :, :, : self.v_head_dim]
attn_output = attn_output.reshape( bsz, q_len, self.num_heads * self.v_head_dim ).contiguous() attn_output = self.o_proj(attn_output)
if not output_attentions: attn_weights = None
return attn_output, attn_weights, past_key_value
def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores.
Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`int`, *optional*): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV2FlashAttention2 __init__. causal = self.is_causal and query_length != 1
# Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] ( query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens, ) = self._upad_input( query_states, key_states, value_states, attention_mask, query_length )
cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, )
attn_output = pad_input( attn_output_unpad, indices_q, batch_size, query_length ) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal, )
return attn_output
def _upad_input( self, query_layer, key_layer, value_layer, attention_mask, query_length ): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k, ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( query_layer, attention_mask )
return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), )
ATTENTION_CLASSES = { "eager": DeepseekV2Attention, "flash_attention_2": DeepseekV2FlashAttention2,
"mla_eager": DeepseekV2Attention, "mla_flash_attention_2": DeepseekV2FlashAttention2,
"mha_eager": LlamaAttention, "mha_flash_attention_2": LlamaFlashAttention2}
class DeepseekV2DecoderLayer(nn.Module): def __init__(self, config: DeepseekV2Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size
if config.use_mla: attn_implementation = "mla_" + config._attn_implementation else: attn_implementation = "mha_" + config._attn_implementation
self.self_attn = ATTENTION_CLASSES[attn_implementation]( config=config, layer_idx=layer_idx )
self.mlp = ( DeepseekV2MoE(config) if ( config.n_routed_experts is not None and layer_idx >= config.first_k_dense_replace and layer_idx % config.moe_layer_freq == 0 ) else DeepseekV2MLP(config) ) self.input_layernorm = DeepseekV2RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) self.post_attention_layernorm = DeepseekV2RMSNorm( config.hidden_size, eps=config.rms_norm_eps )
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, **kwargs, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states """ if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, **kwargs, ) hidden_states = residual + hidden_states
# Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions: outputs += (self_attn_weights,)
if use_cache: outputs += (present_key_value,)
return outputs
DeepseekV2_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Parameters: config ([`DeepseekV2Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights."""
@add_start_docstrings( "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.", DeepseekV2_START_DOCSTRING,)class DeepseekV2PreTrainedModel(PreTrainedModel): config_class = DeepseekV2Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["DeepseekV2DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_cache_class = True
def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
DeepseekV2_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**, - 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see `past_key_values`).
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
- 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.
[What are position IDs?](../glossary#position-ids) past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
Two formats are allowed: - a [`~cache_utils.Cache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format.
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned.
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple."""
@add_start_docstrings( "The bare DeepseekV2 Model outputting raw hidden-states without any specific head on top.", DeepseekV2_START_DOCSTRING,)class DeepseekV2Model(DeepseekV2PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV2DecoderLayer`]
Args: config: DeepseekV2Config """
def __init__(self, config: DeepseekV2Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding( config.vocab_size, config.hidden_size, self.padding_idx ) self.layers = nn.ModuleList( [ DeepseekV2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers) ] ) # print(config._attn_implementation) self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.norm = DeepseekV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.embed_tokens
def set_input_embeddings(self, value): self.embed_tokens = value
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None ) -> Union[Tuple, BaseModelOutputWithPast]: output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict )
# retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers." ) use_cache = False
past_key_values_length = 0 if use_cache: use_legacy_cache = not isinstance(past_key_values, Cache) if use_legacy_cache: past_key_values = DynamicCache.from_legacy_cache(past_key_values) past_key_values_length = past_key_values.get_usable_length(seq_length)
if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device position_ids = torch.arange( past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device, ) position_ids = position_ids.unsqueeze(0)
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = ( attention_mask if (attention_mask is not None and 0 in attention_mask) else None ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length, )
# embed positions hidden_states = inputs_embeds
# decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None
for decoder_layer in self.layers: if output_hidden_states: all_hidden_states += (hidden_states,)
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, attention_mask, position_ids, past_key_values, output_attentions, use_cache, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, )
hidden_states = layer_outputs[0]
if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions: all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
# add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,)
next_cache = None if use_cache: next_cache = ( next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache ) if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, )
class DeepseekV2ForCausalLM(DeepseekV2PreTrainedModel): _tied_weights_keys = ["lm_head.weight"]
def __init__(self, config): super().__init__(config) self.model = DeepseekV2Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.model.embed_tokens
def set_input_embeddings(self, value): self.model.embed_tokens = value
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def set_decoder(self, decoder): self.model = decoder
def get_decoder(self): return self.model
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING) @replace_return_docstrings( output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC ) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
Returns:
Example:
```python >>> from transformers import AutoTokenizer, DeepseekV2ForCausalLM
>>> model = DeepseekV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
>>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict )
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position )
hidden_states = outputs[0] logits = self.lm_head(hidden_states) logits = logits.float()
loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels)
if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs, ): past_length = 0 if past_key_values is not None: if isinstance(past_key_values, Cache): cache_length = past_key_values.get_seq_length() past_length = past_key_values.seen_tokens max_cache_length = past_key_values.get_max_length() else: cache_length = past_length = past_key_values[0][0].shape[2] max_cache_length = None
# Keep only the unprocessed tokens: # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as # input) if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):] # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard # input_ids based on the past_length. elif past_length < input_ids.shape[1]: input_ids = input_ids[:, past_length:] # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask. if ( max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length ): attention_mask = attention_mask[:, -max_cache_length:]
position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -input_ids.shape[1]:]
if self.generation_config.cache_implementation == "static": # generation with static cache cache_position = kwargs.get("cache_position", None) if cache_position is None: past_length = 0 else: past_length = cache_position[-1] + 1 input_ids = input_ids[:, past_length:] position_ids = position_ids[:, past_length:]
# TODO @gante we should only keep a `cache_position` in generate, and do +=1. # same goes for position ids. Could also help with continued generation. cache_position = torch.arange(past_length, past_length + position_ids.shape[-1], device=position_ids.device)
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114 # TODO: use `next_tokens` directly instead. model_inputs = {"input_ids": input_ids.contiguous()}
model_inputs.update( { "position_ids": position_ids.contiguous(), "cache_position": cache_position, "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, } ) return model_inputs
@staticmethod def _reorder_cache(past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: reordered_past += ( tuple( past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past ), ) return reordered_past
@add_start_docstrings( """ The DeepseekV2 Model transformer with a sequence classification head on top (linear layer).
[`DeepseekV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do.
Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, DeepseekV2_START_DOCSTRING,)class DeepseekV2ForSequenceClassification(DeepseekV2PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.model = DeepseekV2Model(config) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self): return self.model.embed_tokens
def set_input_embeddings(self, value): self.model.embed_tokens = value
@add_start_docstrings_to_model_forward(DeepseekV2_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict )
transformer_outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states)
if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0]
if self.config.pad_token_id is None and batch_size != 1: raise ValueError( "Cannot handle batch sizes > 1 if no padding token is defined." ) if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = ( torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 ).to(logits.device) else: sequence_lengths = -1
pooled_logits = logits[ torch.arange(batch_size, device=logits.device), sequence_lengths ]
loss = None if labels is not None: labels = labels.to(logits.device) if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and ( labels.dtype == torch.long or labels.dtype == torch.int ): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct( pooled_logits.view(-1, self.num_labels), labels.view(-1) ) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )123456789101112131415161718192021222324252627{ "additional_special_tokens": [ "<|User|>", "<|Assistant|>" ], "bos_token": { "content": "<|begin▁of▁sentence|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|end▁of▁sentence|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|▁pad▁|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}config.jsonAdded+132
configuration_deepseek_v2.pyAdded+210
conversation.pyAdded+280
deepencoderv2.pyAdded+1956
generation_config.jsonAdded+6
model-00001-of-00002.safetensorsAdded+3
model-00002-of-00002.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_deepseekocr2.pyAdded+2110
modeling_deepseekv2.pyAdded+1998
special_tokens_map.jsonAdded+27
tokenizer.jsonAdded
tokenizer_config.jsonAdded