ykzhang721 commited on
Commit
df0d71b
·
verified ·
1 Parent(s): 90234fb

Upload modelforseminat_v6.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modelforseminat_v6.py +160 -31
modelforseminat_v6.py CHANGED
@@ -551,11 +551,6 @@ class Olmo2ModelForSemiNAT(Olmo2Model):
551
  # pdb.set_trace()
552
 
553
  ################################ 并行处理 #################################
554
-
555
- # pdb.set_trace()
556
-
557
- # 这里attention_mask没有用,因为encoder没有attention层
558
-
559
 
560
  length_ground_truth = None
561
  if not inference or is_prefill:
@@ -662,18 +657,15 @@ class Olmo2ModelForSemiNAT(Olmo2Model):
662
  assert length == max_chunk_num
663
 
664
 
665
-
666
  nat_input_embeddings, nat_attention_mask = self.repeat_with_limit_and_pad_chunk_ar(
667
  hidden_states, inputs_embeds, accumu_num, length_ground_truth, self.chunk_size_limit, skip_val=-100)
668
  # pdb.set_trace()
669
 
670
-
671
  if self.mlp:
672
  nat_input_embeddings = self.linear_projection(nat_input_embeddings)
673
 
674
 
675
-
676
-
677
  # 处理attention
678
  mask_nat_attention_mask = self.nat_prepare_4d_full_attention_mask_with_causal(
679
  attention_mask=nat_attention_mask,
@@ -682,7 +674,7 @@ class Olmo2ModelForSemiNAT(Olmo2Model):
682
 
683
  # pdb.set_trace()
684
 
685
- self.decoder = self.decoder.to(dtype=nat_input_embeddings.dtype)
686
  if self.position_embedding_type == "relative":
687
  nar_chunk_position = torch.arange(
688
  0, self.chunk_size_limit).unsqueeze(0).repeat(
@@ -720,30 +712,167 @@ class Olmo2ModelForSemiNAT(Olmo2Model):
720
  )
721
 
722
 
723
- def repeat_with_limit_and_pad_chunk_ar(self, x: torch.Tensor, inputs_embeds: torch.Tensor, accumu_num: int, repeat_counts: torch.Tensor, chunk_limit: int, skip_val: int = -100):
724
- bs, length, hidden_size = x.size()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
725
  # pdb.set_trace()
726
- acc_num = 0
727
- out_tensor = torch.zeros(accumu_num, chunk_limit, hidden_size).to(x.device).to(x.dtype)
728
- for b in range(bs):
729
- start = repeat_counts[b, 0].item()
730
- for i in range(1,length):
731
- if repeat_counts[b, i] != -100:
732
- out_tensor[acc_num,0,:] = x[b,i-1,:]
733
- end = min(repeat_counts[b, i], chunk_limit-1)
734
- out_tensor[acc_num, 1:end+1, :] = inputs_embeds[b, start:start+end, :]
735
- acc_num += 1
736
- start += repeat_counts[b, i]
737
- else:
738
- break
739
- # pdb.set_trace()
740
- assert acc_num == accumu_num
741
 
742
- # Compute mask: shape (accumu_num, chunk_limit)
743
- mask = (out_tensor.abs().sum(dim=-1) != 0).to(torch.bfloat16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
744
  return out_tensor, mask
745
 
746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  def build_slice_matrix(self, input_ids, slice_pos: torch.Tensor):
748
  bs, num_slices = slice_pos.shape
749
  seq_len = input_ids.size(1)
@@ -1167,14 +1296,14 @@ class Olmo2ForCausalLMForSemiNAT(Olmo2ForCausalLM):
1167
  # pdb.set_trace()
1168
  try:
1169
  nar_labels[chunk, :length_ground_truth[b, i]] = labels[
1170
- b, last_cut + 1:slice_pos[b, i] + 1]
1171
  except:
1172
  pdb.set_trace()
1173
  last_cut = slice_pos[b, i]
1174
  chunk += 1
1175
  else:
1176
  break
1177
- # pdb.set_trace()
1178
  return nar_labels
1179
 
1180
  def fixed_cross_entropy(self,
 
551
  # pdb.set_trace()
552
 
553
  ################################ 并行处理 #################################
 
 
 
 
 
554
 
555
  length_ground_truth = None
556
  if not inference or is_prefill:
 
657
  assert length == max_chunk_num
658
 
659
 
660
+ # pdb.set_trace()
661
  nat_input_embeddings, nat_attention_mask = self.repeat_with_limit_and_pad_chunk_ar(
662
  hidden_states, inputs_embeds, accumu_num, length_ground_truth, self.chunk_size_limit, skip_val=-100)
663
  # pdb.set_trace()
664
 
 
665
  if self.mlp:
666
  nat_input_embeddings = self.linear_projection(nat_input_embeddings)
667
 
668
 
 
 
669
  # 处理attention
670
  mask_nat_attention_mask = self.nat_prepare_4d_full_attention_mask_with_causal(
671
  attention_mask=nat_attention_mask,
 
674
 
675
  # pdb.set_trace()
676
 
677
+ # self.decoder = self.decoder.to(dtype=nat_input_embeddings.dtype)
678
  if self.position_embedding_type == "relative":
679
  nar_chunk_position = torch.arange(
680
  0, self.chunk_size_limit).unsqueeze(0).repeat(
 
712
  )
713
 
714
 
715
+ # def repeat_with_limit_and_pad_chunk_ar(self, x: torch.Tensor, inputs_embeds: torch.Tensor, accumu_num: int, repeat_counts: torch.Tensor, chunk_limit: int, skip_val: int = -100):
716
+ # bs, length, hidden_size = x.size()
717
+ # # pdb.set_trace()
718
+ # acc_num = 0
719
+ # out_tensor = torch.zeros(accumu_num, chunk_limit, hidden_size).to(x.device).to(x.dtype)
720
+ # for b in range(bs):
721
+ # start = repeat_counts[b, 0].item()
722
+ # for i in range(1,length):
723
+ # if repeat_counts[b, i] != -100:
724
+ # out_tensor[acc_num,0,:] = x[b,i-1,:]
725
+ # # end = min(repeat_counts[b, i], chunk_limit-1)
726
+ # end = repeat_counts[b, i] - 1
727
+ # out_tensor[acc_num, 1:end+1, :] = inputs_embeds[b, start:start+end, :]
728
+ # acc_num += 1
729
+ # start += repeat_counts[b, i]
730
+ # else:
731
+ # break
732
+ # # pdb.set_trace()
733
+ # assert acc_num == accumu_num
734
+
735
+ # # Compute mask: shape (accumu_num, chunk_limit)
736
+ # mask = (out_tensor.abs().sum(dim=-1) != 0).to(torch.bfloat16)
737
+ # return out_tensor, mask
738
+
739
+ def repeat_with_limit_and_pad_chunk_ar(
740
+ self,
741
+ x: torch.Tensor, # (bs, L, H)
742
+ inputs_embeds: torch.Tensor, # (bs, L, H)
743
+ accumu_num: int,
744
+ repeat_counts: torch.Tensor, # (bs, L); repeat_counts[b,0]=start; 其余为 Li 或 skip_val
745
+ chunk_limit: int,
746
+ skip_val: int = -100,
747
+ ):
748
+ bs, L, H = x.size()
749
+ device, dtype = x.device, x.dtype
750
+
751
  # pdb.set_trace()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752
 
753
+ # 切出每个样本的 chunk 长度 Li(对应原循环中的 i=1..L-1)
754
+ Li = repeat_counts[:, 1:] # (bs, L-1)
755
+ valid = (Li != skip_val) # (bs, L-1)
756
+ N = int(valid.sum().item()) # 总 chunk 数
757
+
758
+ # 起始位置 start0,并进行边界保护到 [0, L]
759
+ start0 = repeat_counts[:, 0].clamp(min=0, max=L) # (bs,)
760
+
761
+ # 计算每个 chunk 的起点: s_i = start0 + sum_{j< i} Li_j (exclusive cumsum)
762
+ Li_pos = torch.where(valid, Li, torch.zeros_like(Li)) # 仅累计有效位置
763
+ csum = torch.cumsum(Li_pos, dim=1) # (bs, L-1),结束位置
764
+ excl_csum = csum - Li_pos # 开始位置
765
+ start_pos = start0.unsqueeze(1) + excl_csum # 加上基础偏置,
766
+
767
+ # 计算每个 chunk 的拷贝长度 copy_len = max(Li-1, 0)
768
+ copy_len = torch.where(valid, Li - 1, torch.zeros_like(Li)) # 每个chunk取多少token作为输入,-1是因为第0位是chunk hidden位
769
+ copy_len = torch.clamp(copy_len, min=0) # (bs, L-1),
770
+
771
+ # 索引所有有效 (b, i) 位置
772
+ b_idx, i_idx = torch.nonzero(valid, as_tuple=True) # bs是哪个batch,i是batch的哪个位置
773
+ if N != accumu_num:
774
+ raise RuntimeError(
775
+ f"[repeat_with_limit_and_pad_chunk_ar] acc_num({N}) != accumu_num({accumu_num}); 请检查 repeat_counts 与外部统计口径是否一致。"
776
+ )
777
+
778
+ # 准备输出张量
779
+ out_tensor = torch.zeros(N, chunk_limit, H, device=device, dtype=dtype)
780
+ lengths = torch.zeros(N, dtype=torch.long, device=device)
781
+
782
+ # 第 0 列放 AR 种子:x[b, i-1, :]
783
+ ar_src_idx = i_idx # 因为 i_idx 对应原 i-1
784
+ out_tensor[:, 0, :] = x[b_idx, ar_src_idx, :] # (N, H)
785
+
786
+ # 构造用于批量 gather 的二维索引以拷贝 NAR 部分(列 1..)
787
+ C = chunk_limit - 1
788
+ if C > 0 and N > 0:
789
+ # 每个样本的列偏移 0..C-1
790
+ k = torch.arange(C, device=device).unsqueeze(0).expand(N, C) # (N, C)
791
+
792
+ # 对应每行的有效拷贝长度
793
+ copy_len_flat = copy_len[b_idx, i_idx] # (N,)
794
+ start_flat = start_pos[b_idx, i_idx] # (N,)
795
+
796
+ # 有效位置掩码:只在 k < copy_len 时拷贝
797
+ take_mask = k < copy_len_flat.unsqueeze(1) # (N, C),每个chunk有多少个token是原输入embedding copy来的
798
+
799
+ # 计算需要从 inputs_embeds 取的绝对位置
800
+ src_pos = (start_flat.unsqueeze(1) + k).masked_fill(~take_mask, 0) # (N, C)
801
+
802
+ # 展平后一次性 gather
803
+ gather_b = b_idx.repeat_interleave(C) # (N*C,)
804
+ gather_p = src_pos.reshape(-1) # (N*C,)
805
+ gathered = inputs_embeds[gather_b, gather_p, :].reshape(N, C, H) # (N, C, H),哪条样本的哪个位置
806
+
807
+ # 将无效位置置零(保持与原实现一致的填充行为)
808
+ gathered = gathered * take_mask.unsqueeze(-1) # (N, C, H),mask掉的变成0
809
+
810
+ # 写入 out_tensor 的列 1..C
811
+ out_tensor[:, 1:1 + C, :] = gathered
812
+
813
+ # 记录各行有效长度(含第 0 列)
814
+ lengths = 1 + copy_len[b_idx, i_idx]
815
+
816
+ # 基于长度构造 mask,返回 bfloat16(1/0)
817
+ cols = torch.arange(chunk_limit, device=device).unsqueeze(0) # (1, C_total)
818
+ mask_bool = cols < lengths.unsqueeze(1) # (N, C_total)
819
+ mask = mask_bool.to(torch.bfloat16)
820
+
821
  return out_tensor, mask
822
 
823
 
824
+ # def repeat_with_limit_and_pad_chunk_ar(
825
+ # self,
826
+ # x: torch.Tensor, # (bs, L, H)
827
+ # inputs_embeds: torch.Tensor, # (bs, L, H)
828
+ # accumu_num: int,
829
+ # repeat_counts: torch.Tensor, # (bs, L); repeat_counts[b,0]=start; 其余为 Li 或 skip_val
830
+ # chunk_limit: int,
831
+ # skip_val: int = -100,
832
+ # ):
833
+ # bs, L, H = x.size()
834
+ # device, dtype = x.device, x.dtype
835
+
836
+ # acc_num = 0
837
+ # out_tensor = torch.zeros(accumu_num, chunk_limit, H, device=device, dtype=dtype)
838
+ # lengths = torch.zeros(accumu_num, dtype=torch.long, device=device) # 每个chunk的有效长度(含第0位)
839
+
840
+ # for b in range(bs):
841
+ # # 起点:来自 repeat_counts[b,0],做一次边界保护
842
+ # start = int(repeat_counts[b, 0].item())
843
+ # if start < 0: start = 0
844
+ # if start > L: start = L # 超界时后续 copy_len 会变成 0
845
+
846
+ # for i in range(1, L):
847
+ # Li = int(repeat_counts[b, i].item())
848
+ # if Li == skip_val:
849
+ # break
850
+
851
+ # out_tensor[acc_num, 0, :] = x[b, i - 1, :]
852
+ # copy_len = Li - 1
853
+
854
+ # if copy_len > 0:
855
+ # # 左右切片都用 copy_len,确保长度一致
856
+ # out_tensor[acc_num, 1:1 + copy_len, :] = inputs_embeds[b, start:start + copy_len, :]
857
+
858
+ # # 记录该 chunk 的有效长度(包含第0列的AR位)
859
+ # lengths[acc_num] = 1 + copy_len
860
+ # acc_num += 1
861
+ # if acc_num != accumu_num:
862
+ # raise RuntimeError(
863
+ # f"[repeat_with_limit_and_pad_chunk_ar] acc_num({acc_num}) != accumu_num({accumu_num}); "
864
+ # f"请检查 repeat_counts 与外部统计口径是否一致。"
865
+ # )
866
+
867
+ # # 基于长度构造 mask:(accumu_num, chunk_limit);保持返回 dtype 为 bfloat16
868
+ # cols = torch.arange(chunk_limit, device=device).unsqueeze(0) # (1, C)
869
+ # mask_bool = cols < lengths.unsqueeze(1) # (N, C) bool
870
+ # # 与原接口一致:返回 bfloat16(1.0/0.0)
871
+ # mask = mask_bool.to(torch.bfloat16)
872
+
873
+ # return out_tensor, mask
874
+
875
+
876
  def build_slice_matrix(self, input_ids, slice_pos: torch.Tensor):
877
  bs, num_slices = slice_pos.shape
878
  seq_len = input_ids.size(1)
 
1296
  # pdb.set_trace()
1297
  try:
1298
  nar_labels[chunk, :length_ground_truth[b, i]] = labels[
1299
+ b, last_cut + 1:slice_pos[b, i] + 1] #slice_pos是包含尾部token,所以+1
1300
  except:
1301
  pdb.set_trace()
1302
  last_cut = slice_pos[b, i]
1303
  chunk += 1
1304
  else:
1305
  break
1306
+ pdb.set_trace()
1307
  return nar_labels
1308
 
1309
  def fixed_cross_entropy(self,