Crystalcareai commited on
Commit
9446754
·
verified ·
1 Parent(s): c0eaa88

Update modeling_quiet.py

Browse files
Files changed (1) hide show
  1. modeling_quiet.py +162 -99
modeling_quiet.py CHANGED
@@ -1169,7 +1169,7 @@ def nonzero_mean(x, axis=None):
1169
  def loss_mean(x):
1170
  return x.sum() / (x != 0).sum()
1171
 
1172
- class QuietForCausalLM(QuietPreTrainedModel, GenerationMixin):
1173
  _tied_weights_keys = ["lm_head.weight"]
1174
 
1175
  def __init__(self, config):
@@ -1324,91 +1324,91 @@ class QuietForCausalLM(QuietPreTrainedModel, GenerationMixin):
1324
  elif isinstance(module, nn.Embedding):
1325
  nn.init.xavier_uniform_(module.weight)
1326
 
1327
- @torch.no_grad()
1328
- def generate(
1329
- self,
1330
- input_ids: torch.LongTensor,
1331
- attention_mask: Optional[torch.LongTensor] = None,
1332
- **generate_kwargs,
1333
- ) -> torch.LongTensor:
1334
- n_ahead = 8
1335
- n_ahead_talk = 4
1336
- merged_talk_heads = True
1337
-
1338
- if attention_mask is None:
1339
- attention_mask = torch.ones_like(input_ids)
1340
-
1341
- generate_kwargs.update({
1342
- "max_thoughts": n_ahead + n_ahead_talk + 1,
1343
- "merged_talk_heads": merged_talk_heads,
1344
- "merged_lm_and_talk_heads": False,
1345
- "merged_lm_and_think_heads": True,
1346
- "use_concat_talk_head": True,
1347
- "use_shallow_think": True,
1348
- "use_shallow_talk": False,
1349
- "use_complex_think_head": False,
1350
- "use_complex_talk_head": True,
1351
- "use_weighted_talk_head": True,
1352
- })
1353
 
1354
- # Validate stopping criteria
1355
- stopping_criteria = generate_kwargs.pop("stopping_criteria", None)
1356
- if stopping_criteria is not None:
1357
- stopping_criteria = validate_stopping_criteria(
1358
- stopping_criteria,
1359
- self.config,
1360
- )
1361
- stopping_criteria = StoppingCriteriaList(stopping_criteria)
1362
- else:
1363
- stopping_criteria = StoppingCriteriaList()
1364
-
1365
- streamer = generate_kwargs.pop("streamer", None)
1366
- temp = generate_kwargs.pop("temperature", 1.0)
1367
- max_length = generate_kwargs.pop("max_length", 20)
1368
-
1369
- finished_generating = torch.zeros(len(input_ids), dtype=torch.bool, device=input_ids.device)
1370
-
1371
- for cur_token_idx in range(max_length):
1372
- # Sample the next token
1373
- new_ids = self(
1374
- input_ids[~finished_generating],
1375
- attention_mask=attention_mask[~finished_generating]
1376
- )['logits']
1377
 
1378
- # Mask out the start and end thought tokens so we don't accidentally sample them
1379
- new_ids[:, :, self.tokenizer.vocab_size:] = -float("inf")
1380
 
1381
- for list_idx, answer_idx in enumerate((~finished_generating).nonzero(as_tuple=True)[0]):
1382
- # Find the index of the last token that is not padding
1383
- base_answer_ids = input_ids[answer_idx]
1384
- new_answer_ids = new_ids[list_idx]
1385
- last_token_idx = (base_answer_ids != self.tokenizer.pad_token_id).nonzero(as_tuple=True)[0].max()
1386
-
1387
- new_ids_sampled = torch.multinomial(
1388
- torch.nn.functional.softmax(new_answer_ids[last_token_idx] / temp, dim=-1), 1)
1389
-
1390
- # Assign the new id to the last token
1391
- if last_token_idx + 1 >= len(base_answer_ids):
1392
- # Add padding everywhere
1393
- new_padding = torch.full((len(input_ids), 1), self.tokenizer.pad_token_id, dtype=torch.long,
1394
- device=input_ids.device)
1395
- input_ids = torch.cat([input_ids, new_padding], dim=-1)
1396
- attention_mask = torch.cat([attention_mask, torch.zeros_like(new_padding)], dim=-1)
1397
 
1398
- attention_mask[answer_idx, last_token_idx + 1] = 1
1399
- input_ids[answer_idx, last_token_idx + 1] = new_ids_sampled
1400
 
1401
- if new_ids_sampled == self.tokenizer.eos_token_id or new_ids_sampled == self.tokenizer.bos_token_id or new_ids_sampled == self.tokenizer.pad_token_id:
1402
- finished_generating[answer_idx] = 1
1403
 
1404
- if finished_generating.all():
1405
- break
1406
 
1407
- if streamer is not None:
1408
- streamer.put(input_ids)
1409
- streamer.end()
1410
 
1411
- return input_ids
1412
 
1413
  @add_start_docstrings_to_model_forward(QUIET_INPUTS_DOCSTRING)
1414
  @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
@@ -1421,31 +1421,41 @@ class QuietForCausalLM(QuietPreTrainedModel, GenerationMixin):
1421
  inputs_embeds: Optional[torch.FloatTensor] = None,
1422
  labels: Optional[torch.LongTensor] = None,
1423
  use_cache: Optional[bool] = None,
1424
- # output_router_logits: Optional[bool] = None,
1425
  output_attentions: Optional[bool] = None,
1426
  output_hidden_states: Optional[bool] = None,
1427
  return_dict: Optional[bool] = None,
1428
- ) -> Union[Tuple, CausalLMOutputWithPast]:
1429
- r"""
1430
- Args:
1431
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1432
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1433
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1434
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1435
- Returns:
1436
- Example:
1437
- ```python
1438
- >>> from transformers import AutoTokenizer, QuietForCausalLM
1439
- >>> model = QuietForCausalLM.from_pretrained("quietai/Quiet-7B-v0.1")
1440
- >>> tokenizer = AutoTokenizer.from_pretrained("quietai/Quiet-7B-v0.1")
1441
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
1442
- >>> inputs = tokenizer(prompt, return_tensors="pt")
1443
- >>> # Generate
1444
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1445
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1446
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1447
- ```"""
1448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1449
  if not self.training:
1450
  n_ahead_talk_to_restore = self.n_ahead_talk
1451
  n_passes_to_restore = self.n_passes
@@ -2217,6 +2227,59 @@ class QuietForCausalLM(QuietPreTrainedModel, GenerationMixin):
2217
  """,
2218
  QUIET_START_DOCSTRING,
2219
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2220
  # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Quiet, LLAMA->QUIET
2221
  class QuietForSequenceClassification(QuietPreTrainedModel):
2222
  def __init__(self, config):
 
1169
  def loss_mean(x):
1170
  return x.sum() / (x != 0).sum()
1171
 
1172
+ class QuietForCausalLM(QuietPreTrainedModel, QuietGenerationMixin):
1173
  _tied_weights_keys = ["lm_head.weight"]
1174
 
1175
  def __init__(self, config):
 
1324
  elif isinstance(module, nn.Embedding):
1325
  nn.init.xavier_uniform_(module.weight)
1326
 
1327
+ # @torch.no_grad()
1328
+ # def generate(
1329
+ # self,
1330
+ # input_ids: torch.LongTensor,
1331
+ # attention_mask: Optional[torch.LongTensor] = None,
1332
+ # **generate_kwargs,
1333
+ # ) -> torch.LongTensor:
1334
+ # n_ahead = 8
1335
+ # n_ahead_talk = 4
1336
+ # merged_talk_heads = True
1337
+
1338
+ # if attention_mask is None:
1339
+ # attention_mask = torch.ones_like(input_ids)
1340
+
1341
+ # generate_kwargs.update({
1342
+ # "max_thoughts": n_ahead + n_ahead_talk + 1,
1343
+ # "merged_talk_heads": merged_talk_heads,
1344
+ # "merged_lm_and_talk_heads": False,
1345
+ # "merged_lm_and_think_heads": True,
1346
+ # "use_concat_talk_head": True,
1347
+ # "use_shallow_think": True,
1348
+ # "use_shallow_talk": False,
1349
+ # "use_complex_think_head": False,
1350
+ # "use_complex_talk_head": True,
1351
+ # "use_weighted_talk_head": True,
1352
+ # })
1353
 
1354
+ # # Validate stopping criteria
1355
+ # stopping_criteria = generate_kwargs.pop("stopping_criteria", None)
1356
+ # if stopping_criteria is not None:
1357
+ # stopping_criteria = validate_stopping_criteria(
1358
+ # stopping_criteria,
1359
+ # self.config,
1360
+ # )
1361
+ # stopping_criteria = StoppingCriteriaList(stopping_criteria)
1362
+ # else:
1363
+ # stopping_criteria = StoppingCriteriaList()
1364
+
1365
+ # streamer = generate_kwargs.pop("streamer", None)
1366
+ # temp = generate_kwargs.pop("temperature", 1.0)
1367
+ # max_length = generate_kwargs.pop("max_length", 20)
1368
+
1369
+ # finished_generating = torch.zeros(len(input_ids), dtype=torch.bool, device=input_ids.device)
1370
+
1371
+ # for cur_token_idx in range(max_length):
1372
+ # # Sample the next token
1373
+ # new_ids = self(
1374
+ # input_ids[~finished_generating],
1375
+ # attention_mask=attention_mask[~finished_generating]
1376
+ # )['logits']
1377
 
1378
+ # # Mask out the start and end thought tokens so we don't accidentally sample them
1379
+ # new_ids[:, :, self.tokenizer.vocab_size:] = -float("inf")
1380
 
1381
+ # for list_idx, answer_idx in enumerate((~finished_generating).nonzero(as_tuple=True)[0]):
1382
+ # # Find the index of the last token that is not padding
1383
+ # base_answer_ids = input_ids[answer_idx]
1384
+ # new_answer_ids = new_ids[list_idx]
1385
+ # last_token_idx = (base_answer_ids != self.tokenizer.pad_token_id).nonzero(as_tuple=True)[0].max()
1386
+
1387
+ # new_ids_sampled = torch.multinomial(
1388
+ # torch.nn.functional.softmax(new_answer_ids[last_token_idx] / temp, dim=-1), 1)
1389
+
1390
+ # # Assign the new id to the last token
1391
+ # if last_token_idx + 1 >= len(base_answer_ids):
1392
+ # # Add padding everywhere
1393
+ # new_padding = torch.full((len(input_ids), 1), self.tokenizer.pad_token_id, dtype=torch.long,
1394
+ # device=input_ids.device)
1395
+ # input_ids = torch.cat([input_ids, new_padding], dim=-1)
1396
+ # attention_mask = torch.cat([attention_mask, torch.zeros_like(new_padding)], dim=-1)
1397
 
1398
+ # attention_mask[answer_idx, last_token_idx + 1] = 1
1399
+ # input_ids[answer_idx, last_token_idx + 1] = new_ids_sampled
1400
 
1401
+ # if new_ids_sampled == self.tokenizer.eos_token_id or new_ids_sampled == self.tokenizer.bos_token_id or new_ids_sampled == self.tokenizer.pad_token_id:
1402
+ # finished_generating[answer_idx] = 1
1403
 
1404
+ # if finished_generating.all():
1405
+ # break
1406
 
1407
+ # if streamer is not None:
1408
+ # streamer.put(input_ids)
1409
+ # streamer.end()
1410
 
1411
+ # return input_ids
1412
 
1413
  @add_start_docstrings_to_model_forward(QUIET_INPUTS_DOCSTRING)
1414
  @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
 
1421
  inputs_embeds: Optional[torch.FloatTensor] = None,
1422
  labels: Optional[torch.LongTensor] = None,
1423
  use_cache: Optional[bool] = None,
 
1424
  output_attentions: Optional[bool] = None,
1425
  output_hidden_states: Optional[bool] = None,
1426
  return_dict: Optional[bool] = None,
1427
+ **kwargs,
1428
+ ):
1429
+ n_ahead = 8
1430
+ n_ahead_talk = 4
1431
+ merged_talk_heads = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1432
 
1433
+ kwargs.update({
1434
+ "max_thoughts": n_ahead + n_ahead_talk + 1,
1435
+ "merged_talk_heads": merged_talk_heads,
1436
+ "merged_lm_and_talk_heads": False,
1437
+ "merged_lm_and_think_heads": True,
1438
+ "use_concat_talk_head": True,
1439
+ "use_shallow_think": True,
1440
+ "use_shallow_talk": False,
1441
+ "use_complex_think_head": False,
1442
+ "use_complex_talk_head": True,
1443
+ "use_weighted_talk_head": True,
1444
+ })
1445
+
1446
+ return super().forward(
1447
+ input_ids=input_ids,
1448
+ attention_mask=attention_mask,
1449
+ position_ids=position_ids,
1450
+ past_key_values=past_key_values,
1451
+ inputs_embeds=inputs_embeds,
1452
+ labels=labels,
1453
+ use_cache=use_cache,
1454
+ output_attentions=output_attentions,
1455
+ output_hidden_states=output_hidden_states,
1456
+ return_dict=return_dict,
1457
+ **kwargs,
1458
+ )
1459
  if not self.training:
1460
  n_ahead_talk_to_restore = self.n_ahead_talk
1461
  n_passes_to_restore = self.n_passes
 
2227
  """,
2228
  QUIET_START_DOCSTRING,
2229
  )
2230
+
2231
+ class QuietGenerationMixin(GenerationMixin):
2232
+ def generate(self, input_ids, attention_mask=None, **generate_kwargs):
2233
+ if attention_mask is None:
2234
+ attention_mask = torch.ones_like(input_ids)
2235
+
2236
+ max_length = generate_kwargs.get("max_length", 20)
2237
+ temp = generate_kwargs.get("temperature", 1.0)
2238
+
2239
+ finished_generating = torch.zeros(len(input_ids), dtype=torch.bool, device=input_ids.device)
2240
+
2241
+ for cur_token_idx in range(max_length):
2242
+ # Sample the next token
2243
+ new_ids = self(
2244
+ input_ids[~finished_generating],
2245
+ attention_mask=attention_mask[~finished_generating]
2246
+ )['logits']
2247
+
2248
+ # Mask out the start and end thought tokens so we don't accidentally sample them
2249
+ new_ids[:, :, self.tokenizer.vocab_size:] = -float("inf")
2250
+
2251
+ for list_idx, answer_idx in enumerate((~finished_generating).nonzero(as_tuple=True)[0]):
2252
+ # Find the index of the last token that is not padding
2253
+ base_answer_ids = input_ids[answer_idx]
2254
+ new_answer_ids = new_ids[list_idx]
2255
+ last_token_idx = (base_answer_ids != self.tokenizer.pad_token_id).nonzero(as_tuple=True)[0].max()
2256
+
2257
+ new_ids_sampled = torch.multinomial(
2258
+ torch.nn.functional.softmax(new_answer_ids[last_token_idx] / temp, dim=-1), 1)
2259
+
2260
+ # Assign the new id to the last token
2261
+ if last_token_idx + 1 >= len(base_answer_ids):
2262
+ # Add padding everywhere
2263
+ new_padding = torch.full((len(input_ids), 1), self.tokenizer.pad_token_id, dtype=torch.long,
2264
+ device=input_ids.device)
2265
+ input_ids = torch.cat([input_ids, new_padding], dim=-1)
2266
+ attention_mask = torch.cat([attention_mask, torch.zeros_like(new_padding)], dim=-1)
2267
+
2268
+ attention_mask[answer_idx, last_token_idx + 1] = 1
2269
+ input_ids[answer_idx, last_token_idx + 1] = new_ids_sampled
2270
+
2271
+ if new_ids_sampled == self.tokenizer.eos_token_id or new_ids_sampled == self.tokenizer.bos_token_id or new_ids_sampled == self.tokenizer.pad_token_id:
2272
+ finished_generating[answer_idx] = 1
2273
+
2274
+ if finished_generating.all():
2275
+ break
2276
+
2277
+ streamer = generate_kwargs.get("streamer")
2278
+ if streamer is not None:
2279
+ streamer.put(input_ids)
2280
+ streamer.end()
2281
+
2282
+ return input_ids
2283
  # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Quiet, LLAMA->QUIET
2284
  class QuietForSequenceClassification(QuietPreTrainedModel):
2285
  def __init__(self, config):