nvidia-oliver-holworthy commited on
Commit
6bea99e
·
unverified ·
1 Parent(s): f02f56d

Update llama_bidirectional_model.py with support for broader transformers versions

Browse files
Files changed (1) hide show
  1. llama_bidirectional_model.py +186 -138
llama_bidirectional_model.py CHANGED
@@ -1,178 +1,226 @@
1
- from typing import List, Optional, Tuple, Union
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  import torch
4
- import torch.nn.functional as F
5
- from torch import Tensor, nn
6
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
7
- from transformers.cache_utils import Cache, HybridCache
8
- from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
9
- from transformers.modeling_outputs import (
10
- BaseModelOutputWithPast,
11
- SequenceClassifierOutputWithPast,
12
- )
13
  from transformers.models.llama.configuration_llama import LlamaConfig
14
- from transformers.models.llama.modeling_llama import (
15
- LlamaForSequenceClassification,
16
- LlamaModel,
17
- LlamaPreTrainedModel,
18
- )
19
  from transformers.utils import logging
20
 
21
  logger = logging.get_logger(__name__)
22
 
 
 
 
23
 
24
- def pool(last_hidden_states: Tensor, attention_mask: Tensor, pool_type: str) -> Tensor:
25
- last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
 
26
 
27
- if pool_type == "avg":
28
- emb = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
29
- elif pool_type == "weighted_avg":
30
- emb = last_hidden.sum(dim=1)
31
- elif pool_type == "cls":
32
- emb = last_hidden[:, 0]
33
- elif pool_type == "last":
34
- left_padding = attention_mask[:, -1].sum() == attention_mask.shape[0]
35
- if left_padding:
36
- emb = last_hidden[:, -1]
37
- else:
38
- sequence_lengths = attention_mask.sum(dim=1) - 1
39
- batch_size = last_hidden.shape[0]
40
- emb = last_hidden[
41
- torch.arange(batch_size, device=last_hidden.device), sequence_lengths
42
- ]
43
- else:
44
- raise ValueError(f"pool_type {pool_type} not supported")
45
 
46
- return emb
 
 
 
47
 
48
 
49
  class LlamaBidirectionalConfig(LlamaConfig):
 
 
50
  model_type = "llama_bidirec"
51
 
52
  def __init__(
53
- self, pooling="avg", temperature=1.0, **kwargs,
54
- ):
 
 
 
 
 
 
 
 
55
  self.pooling = pooling
56
  self.temperature = temperature
57
- super().__init__(**kwargs,)
58
 
59
 
60
  class LlamaBidirectionalModel(LlamaModel):
 
 
 
 
 
 
 
 
 
 
 
 
61
  config_class = LlamaBidirectionalConfig
62
 
63
- def __init__(self, config: LlamaConfig):
64
  super().__init__(config)
65
  for layer in self.layers:
66
  layer.self_attn.is_causal = False
67
- self.config._attn_implementation = "eager"
68
 
69
- def _update_causal_mask(
70
  self,
71
- attention_mask: torch.Tensor,
72
- input_tensor: torch.Tensor,
73
- cache_position: torch.Tensor,
74
- past_key_values: Cache,
75
- output_attentions: bool,
76
- ):
77
- # Generates bi-directional attention.
78
- causal_mask = _prepare_4d_attention_mask(attention_mask, input_tensor.dtype)
79
- return causal_mask
80
-
81
-
82
- class LlamaBidirectionalForSequenceClassification(LlamaForSequenceClassification):
83
- config_class = LlamaBidirectionalConfig
84
 
85
- def __init__(self, config):
86
- super().__init__(config)
87
- # Releasing the parameters of LlamaModel
88
- # created by parent LlamaForSequenceClassification
89
- del self.model
90
 
91
- self.model = LlamaBidirectionalModel(config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
- # Initialize weights and apply final processing
94
- self.post_init()
 
 
 
 
 
95
 
96
  def forward(
97
  self,
98
- input_ids: Optional[torch.LongTensor] = None,
99
- attention_mask: Optional[torch.Tensor] = None,
100
- position_ids: Optional[torch.LongTensor] = None,
101
- past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
102
- inputs_embeds: Optional[torch.FloatTensor] = None,
103
- labels: Optional[torch.LongTensor] = None,
104
- use_cache: Optional[bool] = None,
105
- output_attentions: Optional[bool] = None,
106
- output_hidden_states: Optional[bool] = None,
107
- return_dict: Optional[bool] = None,
108
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
109
- r"""
110
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
111
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
112
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
113
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
 
 
 
 
 
 
 
 
114
  """
115
- return_dict = (
116
- return_dict if return_dict is not None else self.config.use_return_dict
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  )
118
 
119
- transformer_outputs = self.model(
120
- input_ids,
121
- attention_mask=attention_mask,
122
- position_ids=position_ids,
123
- past_key_values=past_key_values,
124
- inputs_embeds=inputs_embeds,
125
- use_cache=use_cache,
126
- output_attentions=output_attentions,
127
- output_hidden_states=output_hidden_states,
128
- return_dict=return_dict,
129
- )
130
- hidden_states = transformer_outputs[0]
 
 
 
 
131
 
132
- pooled_hidden_states = pool(
133
- last_hidden_states=hidden_states,
134
- attention_mask=attention_mask,
135
- pool_type=self.config.pooling,
136
- )
137
 
138
- pooled_logits = self.score(pooled_hidden_states)
139
- pooled_logits = pooled_logits / self.config.temperature
140
-
141
- loss = None
142
- if labels is not None:
143
- labels = labels.to(logits.device)
144
- if self.config.problem_type is None:
145
- if self.num_labels == 1:
146
- self.config.problem_type = "regression"
147
- elif self.num_labels > 1 and (
148
- labels.dtype == torch.long or labels.dtype == torch.int
149
- ):
150
- self.config.problem_type = "single_label_classification"
151
- else:
152
- self.config.problem_type = "multi_label_classification"
153
-
154
- if self.config.problem_type == "regression":
155
- loss_fct = MSELoss()
156
- if self.num_labels == 1:
157
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
158
- else:
159
- loss = loss_fct(pooled_logits, labels)
160
- elif self.config.problem_type == "single_label_classification":
161
- loss_fct = CrossEntropyLoss()
162
- loss = loss_fct(
163
- pooled_logits.view(-1, self.num_labels), labels.view(-1)
164
- )
165
- elif self.config.problem_type == "multi_label_classification":
166
- loss_fct = BCEWithLogitsLoss()
167
- loss = loss_fct(pooled_logits, labels)
168
- if not return_dict:
169
- output = (pooled_logits,) + transformer_outputs[1:]
170
- return ((loss,) + output) if loss is not None else output
171
-
172
- return SequenceClassifierOutputWithPast(
173
- loss=loss,
174
- logits=pooled_logits,
175
- past_key_values=transformer_outputs.past_key_values,
176
- hidden_states=transformer_outputs.hidden_states,
177
- attentions=transformer_outputs.attentions,
178
  )
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0.
3
+ """
4
+ Bidirectional Llama model for embedding tasks.
5
+
6
+ This module provides a modified LlamaModel that uses bidirectional (non-causal)
7
+ attention, suitable for generating embeddings where each token should attend
8
+ to all other tokens in the sequence.
9
+
10
+ Supports transformers version 4.44 and above with a unified forward() implementation.
11
+
12
+ Version compatibility notes:
13
+ - transformers 4.47: Setting _attn_implementation in __init__ had no effect due to
14
+ attention initialization order
15
+ - transformers 4.48+: Attention refactor (transformers#35235) activated the
16
+ _attn_implementation setting, which defaulted to "eager" instead of "sdpa"
17
+ - transformers < 4.53: LlamaModel has _update_causal_mask method that can be overridden
18
+ - transformers 4.53+: _update_causal_mask removed; masking moved to masking_utils module,
19
+ necessitating a full forward() override for custom attention masks
20
+ - transformers < 4.54: Decoder layer returns tuple, uses past_key_value (singular)
21
+ - transformers 4.54-4.55: Decoder layer returns tensor, uses past_key_value (singular)
22
+ - transformers 4.56+: Decoder layer returns tensor, uses past_key_values (plural),
23
+ DynamicCache accepts config parameter
24
+ - transformers 5.0+: Has native create_bidirectional_mask in masking_utils
25
+ """
26
+
27
+ import inspect
28
 
29
  import torch
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_outputs import BaseModelOutputWithPast
 
 
 
 
 
 
 
32
  from transformers.models.llama.configuration_llama import LlamaConfig
33
+ from transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaModel
 
 
 
 
34
  from transformers.utils import logging
35
 
36
  logger = logging.get_logger(__name__)
37
 
38
+ # Check if native create_bidirectional_mask exists (transformers >= 5.0)
39
+ try:
40
+ from transformers.masking_utils import create_bidirectional_mask
41
 
42
+ _HAS_NATIVE_BIDIRECTIONAL_MASK = True
43
+ except ImportError:
44
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
45
 
46
+ _HAS_NATIVE_BIDIRECTIONAL_MASK = False
47
+
48
+ # Detect API differences via introspection
49
+ _decoder_forward_params = inspect.signature(LlamaDecoderLayer.forward).parameters
50
+ _dynamic_cache_init_params = inspect.signature(DynamicCache.__init__).parameters
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # past_key_value (singular) in < 4.56, past_key_values (plural) in >= 4.56
53
+ _USE_PLURAL_CACHE_PARAM = "past_key_values" in _decoder_forward_params
54
+ # DynamicCache accepts config parameter in >= 4.56
55
+ _DYNAMIC_CACHE_ACCEPTS_CONFIG = "config" in _dynamic_cache_init_params
56
 
57
 
58
  class LlamaBidirectionalConfig(LlamaConfig):
59
+ """Configuration for LlamaBidirectionalModel with pooling and temperature settings."""
60
+
61
  model_type = "llama_bidirec"
62
 
63
  def __init__(
64
+ self, pooling: str = "avg", temperature: float = 1.0, **kwargs
65
+ ) -> None:
66
+ """
67
+ Initialize bidirectional Llama configuration.
68
+
69
+ Args:
70
+ pooling: Pooling strategy for embeddings ("avg", "cls", "last", etc.)
71
+ temperature: Temperature scaling for embeddings
72
+ **kwargs: Additional arguments passed to LlamaConfig
73
+ """
74
  self.pooling = pooling
75
  self.temperature = temperature
76
+ super().__init__(**kwargs)
77
 
78
 
79
  class LlamaBidirectionalModel(LlamaModel):
80
+ """
81
+ LlamaModel modified to use bidirectional (non-causal) attention.
82
+
83
+ In standard Llama, each token can only attend to previous tokens (causal attention).
84
+ This model removes that restriction, allowing each token to attend to all tokens
85
+ in the sequence, which is useful for embedding tasks.
86
+
87
+ The key modifications are:
88
+ 1. Setting is_causal=False on all attention layers
89
+ 2. Using a bidirectional attention mask instead of causal mask
90
+ """
91
+
92
  config_class = LlamaBidirectionalConfig
93
 
94
+ def __init__(self, config: LlamaConfig) -> None:
95
  super().__init__(config)
96
  for layer in self.layers:
97
  layer.self_attn.is_causal = False
 
98
 
99
+ def _create_bidirectional_mask(
100
  self,
101
+ input_embeds: torch.Tensor,
102
+ attention_mask: torch.Tensor | None,
103
+ ) -> torch.Tensor | None:
104
+ """
105
+ Create bidirectional attention mask.
 
 
 
 
 
 
 
 
106
 
107
+ Args:
108
+ input_embeds: Input embeddings tensor of shape (batch_size, seq_len, hidden_size)
109
+ attention_mask: Optional 2D attention mask of shape (batch_size, seq_len)
110
+ where 1 indicates tokens to attend to and 0 indicates masked tokens
 
111
 
112
+ Returns:
113
+ 4D attention mask suitable for the attention implementation, or None
114
+ if no masking is needed
115
+ """
116
+ if attention_mask is None:
117
+ return None
118
+
119
+ if _HAS_NATIVE_BIDIRECTIONAL_MASK:
120
+ return create_bidirectional_mask(
121
+ config=self.config,
122
+ input_embeds=input_embeds,
123
+ attention_mask=attention_mask,
124
+ )
125
+
126
+ # Fallback for transformers < 5.0 without create_bidirectional_mask
127
 
128
+ # Flash attention handles 2D masks internally; only pass mask if there
129
+ # are actually masked tokens (zeros), otherwise return None for efficiency
130
+ if getattr(self.config, "_attn_implementation", None) == "flash_attention_2":
131
+ has_masked_tokens = (attention_mask == 0).any()
132
+ return attention_mask if has_masked_tokens else None
133
+
134
+ return _prepare_4d_attention_mask(attention_mask, input_embeds.dtype)
135
 
136
  def forward(
137
  self,
138
+ input_ids: torch.LongTensor | None = None,
139
+ attention_mask: torch.Tensor | None = None,
140
+ position_ids: torch.LongTensor | None = None,
141
+ past_key_values: Cache | None = None,
142
+ inputs_embeds: torch.FloatTensor | None = None,
143
+ cache_position: torch.LongTensor | None = None,
144
+ use_cache: bool | None = None,
145
+ **kwargs,
146
+ ) -> BaseModelOutputWithPast:
147
+ """
148
+ Forward pass with bidirectional attention.
149
+
150
+ Args:
151
+ input_ids: Input token IDs of shape (batch_size, seq_len)
152
+ attention_mask: Attention mask of shape (batch_size, seq_len)
153
+ position_ids: Position IDs for rotary embeddings
154
+ past_key_values: Cached key/value states for incremental decoding
155
+ inputs_embeds: Pre-computed input embeddings (alternative to input_ids)
156
+ cache_position: Position indices for cache updates
157
+ use_cache: Whether to return cached key/value states
158
+ **kwargs: Additional arguments passed to decoder layers
159
+
160
+ Returns:
161
+ BaseModelOutputWithPast containing last_hidden_state and past_key_values
162
  """
163
+ if (input_ids is None) ^ (inputs_embeds is not None):
164
+ raise ValueError(
165
+ "You must specify exactly one of input_ids or inputs_embeds"
166
+ )
167
+
168
+ if inputs_embeds is None:
169
+ inputs_embeds = self.embed_tokens(input_ids)
170
+
171
+ # Initialize cache if needed
172
+ if use_cache and past_key_values is None:
173
+ if _DYNAMIC_CACHE_ACCEPTS_CONFIG:
174
+ past_key_values = DynamicCache(config=self.config)
175
+ else:
176
+ past_key_values = DynamicCache()
177
+
178
+ if cache_position is None:
179
+ past_seen_tokens = (
180
+ past_key_values.get_seq_length() if past_key_values is not None else 0
181
+ )
182
+ cache_position = torch.arange(
183
+ past_seen_tokens,
184
+ past_seen_tokens + inputs_embeds.shape[1],
185
+ device=inputs_embeds.device,
186
+ )
187
+
188
+ if position_ids is None:
189
+ position_ids = cache_position.unsqueeze(0)
190
+
191
+ bidirectional_mask = self._create_bidirectional_mask(
192
+ inputs_embeds, attention_mask
193
  )
194
 
195
+ hidden_states = inputs_embeds
196
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
197
+
198
+ # Build decoder layer kwargs with correct cache parameter name
199
+ # (past_key_value in < 4.56, past_key_values in >= 4.56)
200
+ layer_kwargs = {
201
+ "attention_mask": bidirectional_mask,
202
+ "position_ids": position_ids,
203
+ "use_cache": use_cache,
204
+ "cache_position": cache_position,
205
+ "position_embeddings": position_embeddings,
206
+ }
207
+ if _USE_PLURAL_CACHE_PARAM:
208
+ layer_kwargs["past_key_values"] = past_key_values
209
+ else:
210
+ layer_kwargs["past_key_value"] = past_key_values
211
 
212
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
213
+ layer_outputs = decoder_layer(hidden_states, **layer_kwargs)
 
 
 
214
 
215
+ # Decoder returns tuple in < 4.54, tensor in >= 4.54
216
+ if isinstance(layer_outputs, tuple):
217
+ hidden_states = layer_outputs[0]
218
+ else:
219
+ hidden_states = layer_outputs
220
+
221
+ hidden_states = self.norm(hidden_states)
222
+
223
+ return BaseModelOutputWithPast(
224
+ last_hidden_state=hidden_states,
225
+ past_key_values=past_key_values,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  )