Taykhoom commited on
Commit
dabd1d9
·
verified ·
1 Parent(s): b932f65

Fix model correctness and Hugging Face compatibility

Browse files
Files changed (3) hide show
  1. README.md +1 -2
  2. modeling_rnamsm.py +13 -5
  3. tokenization_rnamsm.py +59 -5
README.md CHANGED
@@ -192,8 +192,7 @@ this is `(batch, 1, seqlen, embed_dim)`.
192
  ## Credits
193
 
194
  Original model and code by Zhang et al. Source: [GitHub](https://github.com/yikunpku/RNA-MSM).
195
- The HF conversion code was authored primarily by [Claude Code](https://claude.ai/code)
196
- and reviewed manually by Taykhoom Dalal.
197
 
198
  ## License
199
 
 
192
  ## Credits
193
 
194
  Original model and code by Zhang et al. Source: [GitHub](https://github.com/yikunpku/RNA-MSM).
195
+ Hugging Face port maintained by Taykhoom Dalal.
 
196
 
197
  ## License
198
 
modeling_rnamsm.py CHANGED
@@ -100,8 +100,14 @@ class RowSelfAttention(nn.Module):
100
  self.out_proj = nn.Linear(embed_dim, embed_dim)
101
  self.dropout_module = nn.Dropout(dropout)
102
 
103
- def align_scaling(self, q):
104
- return self.scaling / math.sqrt(q.size(0))
 
 
 
 
 
 
105
 
106
  def compute_attention_weights(self, x, scaling, padding_mask=None):
107
  num_rows, num_cols, batch_size, embed_dim = x.size()
@@ -126,7 +132,7 @@ class RowSelfAttention(nn.Module):
126
  def _batched_forward(self, x, padding_mask=None):
127
  num_rows, num_cols, batch_size, _ = x.size()
128
  max_rows = max(1, self.max_tokens_per_msa // num_cols)
129
- scaling = self.align_scaling(x)
130
  attns = 0
131
  for start in range(0, num_rows, max_rows):
132
  pm = padding_mask[:, start:start + max_rows] if padding_mask is not None else None
@@ -141,7 +147,7 @@ class RowSelfAttention(nn.Module):
141
  num_rows, num_cols, batch_size, _ = x.size()
142
  if num_rows * num_cols > self.max_tokens_per_msa and not torch.is_grad_enabled():
143
  return self._batched_forward(x, self_attn_padding_mask)
144
- scaling = self.align_scaling(x)
145
  attn_weights = self.compute_attention_weights(x, scaling, self_attn_padding_mask)
146
  attn_probs = attn_weights.softmax(-1)
147
  attn_probs = self.dropout_module(attn_probs)
@@ -341,7 +347,9 @@ class RNAMSMModel(RNAMSMPreTrainedModel):
341
  if output_hidden_states:
342
  all_hidden_states.append(x.permute(2, 0, 1, 3))
343
  if output_attentions:
344
- all_row_attentions.append(row_attn)
 
 
345
  all_col_attentions.append(col_attn)
346
 
347
  x = self.emb_layer_norm_after(x)
 
100
  self.out_proj = nn.Linear(embed_dim, embed_dim)
101
  self.dropout_module = nn.Dropout(dropout)
102
 
103
+ def align_scaling(self, q, padding_mask=None):
104
+ if padding_mask is None:
105
+ return self.scaling / math.sqrt(q.size(0))
106
+ valid_rows = (~padding_mask).any(dim=-1).sum(dim=1).clamp_min(1)
107
+ return (
108
+ self.scaling
109
+ / valid_rows.to(device=q.device, dtype=q.dtype).sqrt()
110
+ ).view(1, 1, -1, 1, 1)
111
 
112
  def compute_attention_weights(self, x, scaling, padding_mask=None):
113
  num_rows, num_cols, batch_size, embed_dim = x.size()
 
132
  def _batched_forward(self, x, padding_mask=None):
133
  num_rows, num_cols, batch_size, _ = x.size()
134
  max_rows = max(1, self.max_tokens_per_msa // num_cols)
135
+ scaling = self.align_scaling(x, padding_mask)
136
  attns = 0
137
  for start in range(0, num_rows, max_rows):
138
  pm = padding_mask[:, start:start + max_rows] if padding_mask is not None else None
 
147
  num_rows, num_cols, batch_size, _ = x.size()
148
  if num_rows * num_cols > self.max_tokens_per_msa and not torch.is_grad_enabled():
149
  return self._batched_forward(x, self_attn_padding_mask)
150
+ scaling = self.align_scaling(x, self_attn_padding_mask)
151
  attn_weights = self.compute_attention_weights(x, scaling, self_attn_padding_mask)
152
  attn_probs = attn_weights.softmax(-1)
153
  attn_probs = self.dropout_module(attn_probs)
 
347
  if output_hidden_states:
348
  all_hidden_states.append(x.permute(2, 0, 1, 3))
349
  if output_attentions:
350
+ all_row_attentions.append(
351
+ row_attn.permute(1, 0, 2, 3).contiguous()
352
+ )
353
  all_col_attentions.append(col_attn)
354
 
355
  x = self.emb_layer_norm_after(x)
tokenization_rnamsm.py CHANGED
@@ -112,8 +112,8 @@ class RNAMSMTokenizer(PreTrainedTokenizer):
112
 
113
  def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
114
  if token_ids_1 is None:
115
- return [0] + token_ids_0
116
- return [0] + token_ids_0 + [0] + token_ids_1
117
 
118
  def __call__(
119
  self,
@@ -141,10 +141,30 @@ class RNAMSMTokenizer(PreTrainedTokenizer):
141
  encoded = []
142
  for seq in sequences:
143
  ids = self._tokenize_single(seq, add_special_tokens)
 
 
 
 
 
 
 
 
 
 
 
144
  encoded.append(ids)
145
 
146
- if padding and len(encoded) > 1:
147
- max_len = max(len(ids) for ids in encoded)
 
 
 
 
 
 
 
 
 
148
  pad_id = self.pad_token_id
149
  encoded = [ids + [pad_id] * (max_len - len(ids)) for ids in encoded]
150
 
@@ -160,7 +180,28 @@ class RNAMSMTokenizer(PreTrainedTokenizer):
160
  return BatchEncoding({"input_ids": input_ids, "attention_mask": attention_mask})
161
 
162
  def _tokenize_single(self, sequence, add_special_tokens=True):
163
- tokens = list(sequence)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  ids = [self._convert_token_to_id(t) for t in tokens]
165
  if add_special_tokens:
166
  ids = [self.cls_token_id] + ids
@@ -187,11 +228,24 @@ class RNAMSMTokenizer(PreTrainedTokenizer):
187
  if isinstance(msas[0], str):
188
  msas = [msas]
189
 
 
 
 
 
 
 
 
 
190
  max_rows = max(len(msa) for msa in msas)
191
  max_seqlen = max(
192
  len(self._tokenize_single(seq, add_special_tokens))
193
  for msa in msas for seq in msa
194
  )
 
 
 
 
 
195
 
196
  pad_id = self.pad_token_id
197
  batch_ids = []
 
112
 
113
  def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
114
  if token_ids_1 is None:
115
+ return [0] * (len(token_ids_0) + 1)
116
+ return [0] * (len(token_ids_0) + 1) + [1] * (len(token_ids_1) + 1)
117
 
118
  def __call__(
119
  self,
 
141
  encoded = []
142
  for seq in sequences:
143
  ids = self._tokenize_single(seq, add_special_tokens)
144
+ effective_max_length = max_length
145
+ if truncation and effective_max_length is None:
146
+ effective_max_length = self.model_max_length
147
+ if effective_max_length is not None and len(ids) > effective_max_length:
148
+ if truncation:
149
+ ids = ids[:effective_max_length]
150
+ else:
151
+ raise ValueError(
152
+ f"Encoded length {len(ids)} exceeds max_length "
153
+ f"{effective_max_length}; enable truncation."
154
+ )
155
  encoded.append(ids)
156
 
157
+ if padding:
158
+ if padding == "max_length":
159
+ if max_length is None:
160
+ max_length = self.model_max_length
161
+ max_len = max_length
162
+ else:
163
+ max_len = max(len(ids) for ids in encoded)
164
+ if any(len(ids) > max_len for ids in encoded):
165
+ raise ValueError(
166
+ "Cannot pad sequences that exceed the requested length."
167
+ )
168
  pad_id = self.pad_token_id
169
  encoded = [ids + [pad_id] * (max_len - len(ids)) for ids in encoded]
170
 
 
180
  return BatchEncoding({"input_ids": input_ids, "attention_mask": attention_mask})
181
 
182
  def _tokenize_single(self, sequence, add_special_tokens=True):
183
+ tokens = []
184
+ position = 0
185
+ special_tokens = sorted(
186
+ self.all_special_tokens,
187
+ key=len,
188
+ reverse=True,
189
+ )
190
+ while position < len(sequence):
191
+ special = next(
192
+ (
193
+ token
194
+ for token in special_tokens
195
+ if sequence.startswith(token, position)
196
+ ),
197
+ None,
198
+ )
199
+ if special is not None:
200
+ tokens.append(special)
201
+ position += len(special)
202
+ else:
203
+ tokens.append(sequence[position])
204
+ position += 1
205
  ids = [self._convert_token_to_id(t) for t in tokens]
206
  if add_special_tokens:
207
  ids = [self.cls_token_id] + ids
 
228
  if isinstance(msas[0], str):
229
  msas = [msas]
230
 
231
+ for msa in msas:
232
+ if not msa:
233
+ raise ValueError("MSAs must contain at least one sequence.")
234
+ if len({len(sequence) for sequence in msa}) != 1:
235
+ raise ValueError(
236
+ "All sequences in an MSA must have equal aligned length."
237
+ )
238
+
239
  max_rows = max(len(msa) for msa in msas)
240
  max_seqlen = max(
241
  len(self._tokenize_single(seq, add_special_tokens))
242
  for msa in msas for seq in msa
243
  )
244
+ if max_seqlen > self.model_max_length:
245
+ raise ValueError(
246
+ f"Encoded MSA length {max_seqlen} exceeds model_max_length "
247
+ f"{self.model_max_length}."
248
+ )
249
 
250
  pad_id = self.pad_token_id
251
  batch_ids = []