Ink commited on
Commit
392117b
·
unverified ·
1 Parent(s): 6ffeb66

Fix realtime entropy patching (#26)

Browse files

* allow loading of the entropy model directly

* remove unused argument

* remove spammy warning

* allow patch_batch_size to be adjusted in the forward() method

* revert to original patcher style, fix warning

* allow grads when calculating entropies

* fix grad flow

* return preds from calculate_entropies()

* remove legacy arg

* fix an error with monotonicity and small sequence lengths

* ensure patcher is serializable

* revert patcher to original

* remove unused import

bytelatent/data/patcher.py CHANGED
@@ -2,6 +2,7 @@
2
  import math
3
  import time
4
  from collections import defaultdict
 
5
  from enum import Enum
6
 
7
  import torch
@@ -58,7 +59,11 @@ def entropy(scores):
58
 
59
 
60
  def calculate_entropies(
61
- tokens: torch.tensor, entropy_model, patching_batch_size, device: str | None = None
 
 
 
 
62
  ):
63
  """
64
  tokens: 2D tensor of shape [batch_size, seq_len]
@@ -67,8 +72,12 @@ def calculate_entropies(
67
  Splits the tokens into chunks of size max_length and calculates entropies for each chunk.
68
  Entropy model can be executed on cpu or gpu, specify either 'cuda' or 'cpu' in the device argument.
69
  """
70
- with torch.no_grad():
 
 
 
71
  entropies = []
 
72
  max_length = getattr(entropy_model, "max_length", 8192)
73
  batch_numel = max_length * patching_batch_size
74
  splits = torch.split(tokens.flatten(), batch_numel)
@@ -86,12 +95,15 @@ def calculate_entropies(
86
  pred = pred.reshape(-1, pred.shape[-1])[
87
  : split.numel() - pad_size, :
88
  ] # [batch_size * seq_len, vocab]
 
89
  pred_entropies = entropy(pred)
90
  entropies.append(pred_entropies)
91
 
92
  concat_entropies = torch.cat(entropies, dim=0)
93
  concat_entropies = concat_entropies.reshape(tokens.shape)
94
- return concat_entropies
 
 
95
 
96
 
97
  def patch_start_mask_from_entropy_with_monotonicity(entropies, t):
@@ -101,6 +113,10 @@ def patch_start_mask_from_entropy_with_monotonicity(entropies, t):
101
  returns [bs, seq_len] mask where True indicates the start of a patch
102
  """
103
  bs, seq_len = entropies.shape
 
 
 
 
104
  mask = torch.zeros_like(entropies, dtype=torch.bool)
105
  mask[:, 0] = True
106
 
@@ -123,6 +139,10 @@ def patch_start_mask_global_and_monotonicity(entropies, t, t_add=0):
123
  returns [bs, seq_len] mask where True indicates the start of a patch
124
  """
125
  bs, seq_len = entropies.shape
 
 
 
 
126
  mask = torch.zeros_like(entropies, dtype=torch.bool)
127
  mask[:, 0] = True
128
 
@@ -521,12 +541,12 @@ class Patcher:
521
  if self.log_time:
522
  s = time.time()
523
  if entropies is not None:
524
- scores = torch.tensor(entropies, dtype=torch.float32)
525
  elif preds is not None:
526
  scores = entropy(preds)
527
  else:
528
  start_entropies = time.time()
529
- scores = calculate_entropies(
530
  tokens,
531
  self.entropy_model,
532
  self.patching_batch_size,
 
2
  import math
3
  import time
4
  from collections import defaultdict
5
+ from contextlib import nullcontext
6
  from enum import Enum
7
 
8
  import torch
 
59
 
60
 
61
  def calculate_entropies(
62
+ tokens: torch.tensor,
63
+ entropy_model,
64
+ patching_batch_size,
65
+ device: str | None = None,
66
+ enable_grad: bool = False,
67
  ):
68
  """
69
  tokens: 2D tensor of shape [batch_size, seq_len]
 
72
  Splits the tokens into chunks of size max_length and calculates entropies for each chunk.
73
  Entropy model can be executed on cpu or gpu, specify either 'cuda' or 'cpu' in the device argument.
74
  """
75
+
76
+ grad_context = nullcontext() if enable_grad else torch.no_grad()
77
+
78
+ with grad_context:
79
  entropies = []
80
+ preds = []
81
  max_length = getattr(entropy_model, "max_length", 8192)
82
  batch_numel = max_length * patching_batch_size
83
  splits = torch.split(tokens.flatten(), batch_numel)
 
95
  pred = pred.reshape(-1, pred.shape[-1])[
96
  : split.numel() - pad_size, :
97
  ] # [batch_size * seq_len, vocab]
98
+ preds.append(pred)
99
  pred_entropies = entropy(pred)
100
  entropies.append(pred_entropies)
101
 
102
  concat_entropies = torch.cat(entropies, dim=0)
103
  concat_entropies = concat_entropies.reshape(tokens.shape)
104
+ concat_preds = torch.cat(preds, dim=0)
105
+ concat_preds = concat_preds.reshape(tokens.shape[0], tokens.shape[1], -1)
106
+ return concat_entropies, concat_preds
107
 
108
 
109
  def patch_start_mask_from_entropy_with_monotonicity(entropies, t):
 
113
  returns [bs, seq_len] mask where True indicates the start of a patch
114
  """
115
  bs, seq_len = entropies.shape
116
+
117
+ if seq_len == 0:
118
+ return entropies > t
119
+
120
  mask = torch.zeros_like(entropies, dtype=torch.bool)
121
  mask[:, 0] = True
122
 
 
139
  returns [bs, seq_len] mask where True indicates the start of a patch
140
  """
141
  bs, seq_len = entropies.shape
142
+
143
+ if seq_len == 0:
144
+ return entropies > t
145
+
146
  mask = torch.zeros_like(entropies, dtype=torch.bool)
147
  mask[:, 0] = True
148
 
 
541
  if self.log_time:
542
  s = time.time()
543
  if entropies is not None:
544
+ scores = entropies.to(dtype=torch.float32)
545
  elif preds is not None:
546
  scores = entropy(preds)
547
  else:
548
  start_entropies = time.time()
549
+ scores, _ = calculate_entropies(
550
  tokens,
551
  self.entropy_model,
552
  self.patching_batch_size,
bytelatent/model/local_models.py CHANGED
@@ -199,9 +199,6 @@ class LocalModelBase(nn.Module):
199
  class LocalEncoder(LocalModelBase):
200
  def __init__(self, args: LocalModelArgs):
201
  super().__init__(args)
202
- self.output_proj = (
203
- args.patching_mode in ["entropy", "probmax"]
204
- ) and args.entropy_model_checkpoint_dir is None
205
 
206
  self.apply_transformer = args.use_local_encoder_transformer
207
  self.downsampling_by_pooling = args.downsampling_by_pooling
 
199
  class LocalEncoder(LocalModelBase):
200
  def __init__(self, args: LocalModelArgs):
201
  super().__init__(args)
 
 
 
202
 
203
  self.apply_transformer = args.use_local_encoder_transformer
204
  self.downsampling_by_pooling = args.downsampling_by_pooling
bytelatent/model/utils.py CHANGED
@@ -162,9 +162,6 @@ def create_causal_mask(
162
  return "causal"
163
 
164
  if BLT_SUPPRESS_ATTN_ERROR == 1:
165
- logging.warning(
166
- "SDPA attention being used, which doesn't have specialized attention implementations for block_causal and local_block_causal attention. Allowing model to run since BLT_SUPPRESS_ATTN_ERROR=1"
167
- )
168
  return "causal"
169
  else:
170
  raise ValueError(
 
162
  return "causal"
163
 
164
  if BLT_SUPPRESS_ATTN_ERROR == 1:
 
 
 
165
  return "causal"
166
  else:
167
  raise ValueError(
bytelatent/preprocess/preprocess_entropies.py CHANGED
@@ -117,7 +117,7 @@ def main(
117
  text = get_text(doc)
118
  tokens = torch.tensor(tokenizer.encode(text))
119
  patch_start = time.time()
120
- scores = calculate_entropies(
121
  tokens,
122
  entropy_model,
123
  patching_batch_size,
 
117
  text = get_text(doc)
118
  tokens = torch.tensor(tokenizer.encode(text))
119
  patch_start = time.time()
120
+ scores, _ = calculate_entropies(
121
  tokens,
122
  entropy_model,
123
  patching_batch_size,