Feature Extraction
Transformers
PyTorch
Safetensors
boltz2_automodel
protein-language-model
fastplms
custom_code
Instructions to use Synthyra/Boltz2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Synthyra/Boltz2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="Synthyra/Boltz2", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Synthyra/Boltz2", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload vb_tri_attn_utils.py with huggingface_hub
Browse files- vb_tri_attn_utils.py +380 -380
vb_tri_attn_utils.py
CHANGED
|
@@ -1,380 +1,380 @@
|
|
| 1 |
-
# Copyright 2021 AlQuraishi Laboratory
|
| 2 |
-
#
|
| 3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
-
# you may not use this file except in compliance with the License.
|
| 5 |
-
# You may obtain a copy of the License at
|
| 6 |
-
#
|
| 7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
-
#
|
| 9 |
-
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
-
# See the License for the specific language governing permissions and
|
| 13 |
-
# limitations under the License.
|
| 14 |
-
|
| 15 |
-
from functools import partial
|
| 16 |
-
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
| 17 |
-
|
| 18 |
-
import torch
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
def add(m1, m2, inplace):
|
| 22 |
-
# The first operation in a checkpoint can't be in-place, but it's
|
| 23 |
-
# nice to have in-place addition during inference. Thus...
|
| 24 |
-
if not inplace:
|
| 25 |
-
m1 = m1 + m2
|
| 26 |
-
else:
|
| 27 |
-
m1 += m2
|
| 28 |
-
|
| 29 |
-
return m1
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def permute_final_dims(tensor: torch.Tensor, inds: List[int]):
|
| 33 |
-
zero_index = -1 * len(inds)
|
| 34 |
-
first_inds = list(range(len(tensor.shape[:zero_index])))
|
| 35 |
-
return tensor.permute(first_inds + [zero_index + i for i in inds])
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def is_fp16_enabled():
|
| 39 |
-
# Autocast world
|
| 40 |
-
fp16_enabled = torch.get_autocast_gpu_dtype() == torch.float16
|
| 41 |
-
fp16_enabled = fp16_enabled and torch.is_autocast_enabled()
|
| 42 |
-
|
| 43 |
-
return fp16_enabled
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# With tree_map, a poor man's JAX tree_map
|
| 47 |
-
def dict_map(fn, dic, leaf_type):
|
| 48 |
-
new_dict = {}
|
| 49 |
-
for k, v in dic.items():
|
| 50 |
-
if type(v) is dict:
|
| 51 |
-
new_dict[k] = dict_map(fn, v, leaf_type)
|
| 52 |
-
else:
|
| 53 |
-
new_dict[k] = tree_map(fn, v, leaf_type)
|
| 54 |
-
|
| 55 |
-
return new_dict
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def tree_map(fn, tree, leaf_type):
|
| 59 |
-
if isinstance(tree, dict):
|
| 60 |
-
return dict_map(fn, tree, leaf_type)
|
| 61 |
-
elif isinstance(tree, list):
|
| 62 |
-
return [tree_map(fn, x, leaf_type) for x in tree]
|
| 63 |
-
elif isinstance(tree, tuple):
|
| 64 |
-
return tuple([tree_map(fn, x, leaf_type) for x in tree])
|
| 65 |
-
elif isinstance(tree, leaf_type):
|
| 66 |
-
return fn(tree)
|
| 67 |
-
else:
|
| 68 |
-
raise ValueError(f"Tree of type {type(tree)} not supported")
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
tensor_tree_map = partial(tree_map, leaf_type=torch.Tensor)
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
def flatten_final_dims(t: torch.Tensor, no_dims: int):
|
| 75 |
-
return t.reshape(t.shape[:-no_dims] + (-1,))
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def _fetch_dims(tree):
|
| 79 |
-
shapes = []
|
| 80 |
-
tree_type = type(tree)
|
| 81 |
-
if tree_type is dict:
|
| 82 |
-
for v in tree.values():
|
| 83 |
-
shapes.extend(_fetch_dims(v))
|
| 84 |
-
elif tree_type is list or tree_type is tuple:
|
| 85 |
-
for t in tree:
|
| 86 |
-
shapes.extend(_fetch_dims(t))
|
| 87 |
-
elif tree_type is torch.Tensor:
|
| 88 |
-
shapes.append(tree.shape)
|
| 89 |
-
else:
|
| 90 |
-
raise ValueError("Not supported")
|
| 91 |
-
|
| 92 |
-
return shapes
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
@torch.jit.ignore
|
| 96 |
-
def _flat_idx_to_idx(
|
| 97 |
-
flat_idx: int,
|
| 98 |
-
dims: Tuple[int],
|
| 99 |
-
) -> Tuple[int]:
|
| 100 |
-
idx = []
|
| 101 |
-
for d in reversed(dims):
|
| 102 |
-
idx.append(flat_idx % d)
|
| 103 |
-
flat_idx = flat_idx // d
|
| 104 |
-
|
| 105 |
-
return tuple(reversed(idx))
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
@torch.jit.ignore
|
| 109 |
-
def _get_minimal_slice_set(
|
| 110 |
-
start: Sequence[int],
|
| 111 |
-
end: Sequence[int],
|
| 112 |
-
dims: int,
|
| 113 |
-
start_edges: Optional[Sequence[bool]] = None,
|
| 114 |
-
end_edges: Optional[Sequence[bool]] = None,
|
| 115 |
-
) -> Sequence[Tuple[int]]:
|
| 116 |
-
"""
|
| 117 |
-
Produces an ordered sequence of tensor slices that, when used in
|
| 118 |
-
sequence on a tensor with shape dims, yields tensors that contain every
|
| 119 |
-
leaf in the contiguous range [start, end]. Care is taken to yield a
|
| 120 |
-
short sequence of slices, and perhaps even the shortest possible (I'm
|
| 121 |
-
pretty sure it's the latter).
|
| 122 |
-
|
| 123 |
-
end is INCLUSIVE.
|
| 124 |
-
"""
|
| 125 |
-
|
| 126 |
-
# start_edges and end_edges both indicate whether, starting from any given
|
| 127 |
-
# dimension, the start/end index is at the top/bottom edge of the
|
| 128 |
-
# corresponding tensor, modeled as a tree
|
| 129 |
-
def reduce_edge_list(l):
|
| 130 |
-
tally = 1
|
| 131 |
-
for i in range(len(l)):
|
| 132 |
-
reversed_idx = -1 * (i + 1)
|
| 133 |
-
l[reversed_idx] *= tally
|
| 134 |
-
tally = l[reversed_idx]
|
| 135 |
-
|
| 136 |
-
if start_edges is None:
|
| 137 |
-
start_edges = [s == 0 for s in start]
|
| 138 |
-
reduce_edge_list(start_edges)
|
| 139 |
-
if end_edges is None:
|
| 140 |
-
end_edges = [e == (d - 1) for e, d in zip(end, dims)]
|
| 141 |
-
reduce_edge_list(end_edges)
|
| 142 |
-
|
| 143 |
-
# Base cases. Either start/end are empty and we're done, or the final,
|
| 144 |
-
# one-dimensional tensor can be simply sliced
|
| 145 |
-
if len(start) == 0:
|
| 146 |
-
return [tuple()]
|
| 147 |
-
elif len(start) == 1:
|
| 148 |
-
return [(slice(start[0], end[0] + 1),)]
|
| 149 |
-
|
| 150 |
-
slices = []
|
| 151 |
-
path = []
|
| 152 |
-
|
| 153 |
-
# Dimensions common to start and end can be selected directly
|
| 154 |
-
for s, e in zip(start, end):
|
| 155 |
-
if s == e:
|
| 156 |
-
path.append(slice(s, s + 1))
|
| 157 |
-
else:
|
| 158 |
-
break
|
| 159 |
-
|
| 160 |
-
path = tuple(path)
|
| 161 |
-
divergence_idx = len(path)
|
| 162 |
-
|
| 163 |
-
# start == end, and we're done
|
| 164 |
-
if divergence_idx == len(dims):
|
| 165 |
-
return [tuple(path)]
|
| 166 |
-
|
| 167 |
-
def upper():
|
| 168 |
-
sdi = start[divergence_idx]
|
| 169 |
-
return [
|
| 170 |
-
path + (slice(sdi, sdi + 1),) + s
|
| 171 |
-
for s in _get_minimal_slice_set(
|
| 172 |
-
start[divergence_idx + 1 :],
|
| 173 |
-
[d - 1 for d in dims[divergence_idx + 1 :]],
|
| 174 |
-
dims[divergence_idx + 1 :],
|
| 175 |
-
start_edges=start_edges[divergence_idx + 1 :],
|
| 176 |
-
end_edges=[1 for _ in end_edges[divergence_idx + 1 :]],
|
| 177 |
-
)
|
| 178 |
-
]
|
| 179 |
-
|
| 180 |
-
def lower():
|
| 181 |
-
edi = end[divergence_idx]
|
| 182 |
-
return [
|
| 183 |
-
path + (slice(edi, edi + 1),) + s
|
| 184 |
-
for s in _get_minimal_slice_set(
|
| 185 |
-
[0 for _ in start[divergence_idx + 1 :]],
|
| 186 |
-
end[divergence_idx + 1 :],
|
| 187 |
-
dims[divergence_idx + 1 :],
|
| 188 |
-
start_edges=[1 for _ in start_edges[divergence_idx + 1 :]],
|
| 189 |
-
end_edges=end_edges[divergence_idx + 1 :],
|
| 190 |
-
)
|
| 191 |
-
]
|
| 192 |
-
|
| 193 |
-
# If both start and end are at the edges of the subtree rooted at
|
| 194 |
-
# divergence_idx, we can just select the whole subtree at once
|
| 195 |
-
if start_edges[divergence_idx] and end_edges[divergence_idx]:
|
| 196 |
-
slices.append(path + (slice(start[divergence_idx], end[divergence_idx] + 1),))
|
| 197 |
-
# If just start is at the edge, we can grab almost all of the subtree,
|
| 198 |
-
# treating only the ragged bottom edge as an edge case
|
| 199 |
-
elif start_edges[divergence_idx]:
|
| 200 |
-
slices.append(path + (slice(start[divergence_idx], end[divergence_idx]),))
|
| 201 |
-
slices.extend(lower())
|
| 202 |
-
# Analogous to the previous case, but the top is ragged this time
|
| 203 |
-
elif end_edges[divergence_idx]:
|
| 204 |
-
slices.extend(upper())
|
| 205 |
-
slices.append(
|
| 206 |
-
path + (slice(start[divergence_idx] + 1, end[divergence_idx] + 1),)
|
| 207 |
-
)
|
| 208 |
-
# If both sides of the range are ragged, we need to handle both sides
|
| 209 |
-
# separately. If there's contiguous meat in between them, we can index it
|
| 210 |
-
# in one big chunk
|
| 211 |
-
else:
|
| 212 |
-
slices.extend(upper())
|
| 213 |
-
middle_ground = end[divergence_idx] - start[divergence_idx]
|
| 214 |
-
if middle_ground > 1:
|
| 215 |
-
slices.append(
|
| 216 |
-
path + (slice(start[divergence_idx] + 1, end[divergence_idx]),)
|
| 217 |
-
)
|
| 218 |
-
slices.extend(lower())
|
| 219 |
-
|
| 220 |
-
return [tuple(s) for s in slices]
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
@torch.jit.ignore
|
| 224 |
-
def _chunk_slice(
|
| 225 |
-
t: torch.Tensor,
|
| 226 |
-
flat_start: int,
|
| 227 |
-
flat_end: int,
|
| 228 |
-
no_batch_dims: int,
|
| 229 |
-
) -> torch.Tensor:
|
| 230 |
-
"""
|
| 231 |
-
Equivalent to
|
| 232 |
-
|
| 233 |
-
t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end]
|
| 234 |
-
|
| 235 |
-
but without the need for the initial reshape call, which can be
|
| 236 |
-
memory-intensive in certain situations. The only reshape operations
|
| 237 |
-
in this function are performed on sub-tensors that scale with
|
| 238 |
-
(flat_end - flat_start), the chunk size.
|
| 239 |
-
"""
|
| 240 |
-
|
| 241 |
-
batch_dims = t.shape[:no_batch_dims]
|
| 242 |
-
start_idx = list(_flat_idx_to_idx(flat_start, batch_dims))
|
| 243 |
-
# _get_minimal_slice_set is inclusive
|
| 244 |
-
end_idx = list(_flat_idx_to_idx(flat_end - 1, batch_dims))
|
| 245 |
-
|
| 246 |
-
# Get an ordered list of slices to perform
|
| 247 |
-
slices = _get_minimal_slice_set(
|
| 248 |
-
start_idx,
|
| 249 |
-
end_idx,
|
| 250 |
-
batch_dims,
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
sliced_tensors = [t[s] for s in slices]
|
| 254 |
-
|
| 255 |
-
return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]) for s in sliced_tensors])
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
def chunk_layer(
|
| 259 |
-
layer: Callable,
|
| 260 |
-
inputs: Dict[str, Any],
|
| 261 |
-
chunk_size: int,
|
| 262 |
-
no_batch_dims: int,
|
| 263 |
-
low_mem: bool = False,
|
| 264 |
-
_out: Any = None,
|
| 265 |
-
_add_into_out: bool = False,
|
| 266 |
-
) -> Any:
|
| 267 |
-
"""
|
| 268 |
-
Implements the "chunking" procedure described in section 1.11.8.
|
| 269 |
-
|
| 270 |
-
Layer outputs and inputs are assumed to be simple "pytrees,"
|
| 271 |
-
consisting only of (arbitrarily nested) lists, tuples, and dicts with
|
| 272 |
-
torch.Tensor leaves.
|
| 273 |
-
|
| 274 |
-
Args:
|
| 275 |
-
layer:
|
| 276 |
-
The layer to be applied chunk-wise
|
| 277 |
-
inputs:
|
| 278 |
-
A (non-nested) dictionary of keyworded inputs. All leaves must
|
| 279 |
-
be tensors and must share the same batch dimensions.
|
| 280 |
-
chunk_size:
|
| 281 |
-
The number of sub-batches per chunk. If multiple batch
|
| 282 |
-
dimensions are specified, a "sub-batch" is defined as a single
|
| 283 |
-
indexing of all batch dimensions simultaneously (s.t. the
|
| 284 |
-
number of sub-batches is the product of the batch dimensions).
|
| 285 |
-
no_batch_dims:
|
| 286 |
-
How many of the initial dimensions of each input tensor can
|
| 287 |
-
be considered batch dimensions.
|
| 288 |
-
low_mem:
|
| 289 |
-
Avoids flattening potentially large input tensors. Unnecessary
|
| 290 |
-
in most cases, and is ever so slightly slower than the default
|
| 291 |
-
setting.
|
| 292 |
-
Returns:
|
| 293 |
-
The reassembled output of the layer on the inputs.
|
| 294 |
-
"""
|
| 295 |
-
if not (len(inputs) > 0):
|
| 296 |
-
raise ValueError("Must provide at least one input")
|
| 297 |
-
|
| 298 |
-
initial_dims = [shape[:no_batch_dims] for shape in _fetch_dims(inputs)]
|
| 299 |
-
orig_batch_dims = tuple([max(s) for s in zip(*initial_dims)])
|
| 300 |
-
|
| 301 |
-
def _prep_inputs(t):
|
| 302 |
-
if not low_mem:
|
| 303 |
-
if not sum(t.shape[:no_batch_dims]) == no_batch_dims:
|
| 304 |
-
t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
|
| 305 |
-
t = t.reshape(-1, *t.shape[no_batch_dims:])
|
| 306 |
-
else:
|
| 307 |
-
t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
|
| 308 |
-
return t
|
| 309 |
-
|
| 310 |
-
prepped_inputs = tensor_tree_map(_prep_inputs, inputs)
|
| 311 |
-
prepped_outputs = None
|
| 312 |
-
if _out is not None:
|
| 313 |
-
reshape_fn = lambda t: t.view([-1] + list(t.shape[no_batch_dims:]))
|
| 314 |
-
prepped_outputs = tensor_tree_map(reshape_fn, _out)
|
| 315 |
-
|
| 316 |
-
flat_batch_dim = 1
|
| 317 |
-
for d in orig_batch_dims:
|
| 318 |
-
flat_batch_dim *= d
|
| 319 |
-
|
| 320 |
-
no_chunks = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)
|
| 321 |
-
|
| 322 |
-
i = 0
|
| 323 |
-
out = prepped_outputs
|
| 324 |
-
for _ in range(no_chunks):
|
| 325 |
-
# Chunk the input
|
| 326 |
-
if not low_mem:
|
| 327 |
-
select_chunk = lambda t: t[i : i + chunk_size] if t.shape[0] != 1 else t
|
| 328 |
-
else:
|
| 329 |
-
select_chunk = partial(
|
| 330 |
-
_chunk_slice,
|
| 331 |
-
flat_start=i,
|
| 332 |
-
flat_end=min(flat_batch_dim, i + chunk_size),
|
| 333 |
-
no_batch_dims=len(orig_batch_dims),
|
| 334 |
-
)
|
| 335 |
-
|
| 336 |
-
chunks = tensor_tree_map(select_chunk, prepped_inputs)
|
| 337 |
-
|
| 338 |
-
# Run the layer on the chunk
|
| 339 |
-
output_chunk = layer(**chunks)
|
| 340 |
-
|
| 341 |
-
# Allocate space for the output
|
| 342 |
-
if out is None:
|
| 343 |
-
allocate = lambda t: t.new_zeros((flat_batch_dim,) + t.shape[1:])
|
| 344 |
-
out = tensor_tree_map(allocate, output_chunk)
|
| 345 |
-
|
| 346 |
-
# Put the chunk in its pre-allocated space
|
| 347 |
-
out_type = type(output_chunk)
|
| 348 |
-
if out_type is dict:
|
| 349 |
-
|
| 350 |
-
def assign(d1, d2):
|
| 351 |
-
for k, v in d1.items():
|
| 352 |
-
if type(v) is dict:
|
| 353 |
-
assign(v, d2[k])
|
| 354 |
-
else:
|
| 355 |
-
if _add_into_out:
|
| 356 |
-
v[i : i + chunk_size] += d2[k]
|
| 357 |
-
else:
|
| 358 |
-
v[i : i + chunk_size] = d2[k]
|
| 359 |
-
|
| 360 |
-
assign(out, output_chunk)
|
| 361 |
-
elif out_type is tuple:
|
| 362 |
-
for x1, x2 in zip(out, output_chunk):
|
| 363 |
-
if _add_into_out:
|
| 364 |
-
x1[i : i + chunk_size] += x2
|
| 365 |
-
else:
|
| 366 |
-
x1[i : i + chunk_size] = x2
|
| 367 |
-
elif out_type is torch.Tensor:
|
| 368 |
-
if _add_into_out:
|
| 369 |
-
out[i : i + chunk_size] += output_chunk
|
| 370 |
-
else:
|
| 371 |
-
out[i : i + chunk_size] = output_chunk
|
| 372 |
-
else:
|
| 373 |
-
raise ValueError("Not supported")
|
| 374 |
-
|
| 375 |
-
i += chunk_size
|
| 376 |
-
|
| 377 |
-
reshape = lambda t: t.view(orig_batch_dims + t.shape[1:])
|
| 378 |
-
out = tensor_tree_map(reshape, out)
|
| 379 |
-
|
| 380 |
-
return out
|
|
|
|
| 1 |
+
# Copyright 2021 AlQuraishi Laboratory
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from functools import partial
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def add(m1, m2, inplace):
|
| 22 |
+
# The first operation in a checkpoint can't be in-place, but it's
|
| 23 |
+
# nice to have in-place addition during inference. Thus...
|
| 24 |
+
if not inplace:
|
| 25 |
+
m1 = m1 + m2
|
| 26 |
+
else:
|
| 27 |
+
m1 += m2
|
| 28 |
+
|
| 29 |
+
return m1
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def permute_final_dims(tensor: torch.Tensor, inds: List[int]):
|
| 33 |
+
zero_index = -1 * len(inds)
|
| 34 |
+
first_inds = list(range(len(tensor.shape[:zero_index])))
|
| 35 |
+
return tensor.permute(first_inds + [zero_index + i for i in inds])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def is_fp16_enabled():
|
| 39 |
+
# Autocast world
|
| 40 |
+
fp16_enabled = torch.get_autocast_gpu_dtype() == torch.float16
|
| 41 |
+
fp16_enabled = fp16_enabled and torch.is_autocast_enabled()
|
| 42 |
+
|
| 43 |
+
return fp16_enabled
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# With tree_map, a poor man's JAX tree_map
|
| 47 |
+
def dict_map(fn, dic, leaf_type):
|
| 48 |
+
new_dict = {}
|
| 49 |
+
for k, v in dic.items():
|
| 50 |
+
if type(v) is dict:
|
| 51 |
+
new_dict[k] = dict_map(fn, v, leaf_type)
|
| 52 |
+
else:
|
| 53 |
+
new_dict[k] = tree_map(fn, v, leaf_type)
|
| 54 |
+
|
| 55 |
+
return new_dict
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def tree_map(fn, tree, leaf_type):
|
| 59 |
+
if isinstance(tree, dict):
|
| 60 |
+
return dict_map(fn, tree, leaf_type)
|
| 61 |
+
elif isinstance(tree, list):
|
| 62 |
+
return [tree_map(fn, x, leaf_type) for x in tree]
|
| 63 |
+
elif isinstance(tree, tuple):
|
| 64 |
+
return tuple([tree_map(fn, x, leaf_type) for x in tree])
|
| 65 |
+
elif isinstance(tree, leaf_type):
|
| 66 |
+
return fn(tree)
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError(f"Tree of type {type(tree)} not supported")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
tensor_tree_map = partial(tree_map, leaf_type=torch.Tensor)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def flatten_final_dims(t: torch.Tensor, no_dims: int):
|
| 75 |
+
return t.reshape(t.shape[:-no_dims] + (-1,))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _fetch_dims(tree):
|
| 79 |
+
shapes = []
|
| 80 |
+
tree_type = type(tree)
|
| 81 |
+
if tree_type is dict:
|
| 82 |
+
for v in tree.values():
|
| 83 |
+
shapes.extend(_fetch_dims(v))
|
| 84 |
+
elif tree_type is list or tree_type is tuple:
|
| 85 |
+
for t in tree:
|
| 86 |
+
shapes.extend(_fetch_dims(t))
|
| 87 |
+
elif tree_type is torch.Tensor:
|
| 88 |
+
shapes.append(tree.shape)
|
| 89 |
+
else:
|
| 90 |
+
raise ValueError("Not supported")
|
| 91 |
+
|
| 92 |
+
return shapes
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@torch.jit.ignore
|
| 96 |
+
def _flat_idx_to_idx(
|
| 97 |
+
flat_idx: int,
|
| 98 |
+
dims: Tuple[int],
|
| 99 |
+
) -> Tuple[int]:
|
| 100 |
+
idx = []
|
| 101 |
+
for d in reversed(dims):
|
| 102 |
+
idx.append(flat_idx % d)
|
| 103 |
+
flat_idx = flat_idx // d
|
| 104 |
+
|
| 105 |
+
return tuple(reversed(idx))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@torch.jit.ignore
|
| 109 |
+
def _get_minimal_slice_set(
|
| 110 |
+
start: Sequence[int],
|
| 111 |
+
end: Sequence[int],
|
| 112 |
+
dims: int,
|
| 113 |
+
start_edges: Optional[Sequence[bool]] = None,
|
| 114 |
+
end_edges: Optional[Sequence[bool]] = None,
|
| 115 |
+
) -> Sequence[Tuple[int]]:
|
| 116 |
+
"""
|
| 117 |
+
Produces an ordered sequence of tensor slices that, when used in
|
| 118 |
+
sequence on a tensor with shape dims, yields tensors that contain every
|
| 119 |
+
leaf in the contiguous range [start, end]. Care is taken to yield a
|
| 120 |
+
short sequence of slices, and perhaps even the shortest possible (I'm
|
| 121 |
+
pretty sure it's the latter).
|
| 122 |
+
|
| 123 |
+
end is INCLUSIVE.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
# start_edges and end_edges both indicate whether, starting from any given
|
| 127 |
+
# dimension, the start/end index is at the top/bottom edge of the
|
| 128 |
+
# corresponding tensor, modeled as a tree
|
| 129 |
+
def reduce_edge_list(l):
|
| 130 |
+
tally = 1
|
| 131 |
+
for i in range(len(l)):
|
| 132 |
+
reversed_idx = -1 * (i + 1)
|
| 133 |
+
l[reversed_idx] *= tally
|
| 134 |
+
tally = l[reversed_idx]
|
| 135 |
+
|
| 136 |
+
if start_edges is None:
|
| 137 |
+
start_edges = [s == 0 for s in start]
|
| 138 |
+
reduce_edge_list(start_edges)
|
| 139 |
+
if end_edges is None:
|
| 140 |
+
end_edges = [e == (d - 1) for e, d in zip(end, dims)]
|
| 141 |
+
reduce_edge_list(end_edges)
|
| 142 |
+
|
| 143 |
+
# Base cases. Either start/end are empty and we're done, or the final,
|
| 144 |
+
# one-dimensional tensor can be simply sliced
|
| 145 |
+
if len(start) == 0:
|
| 146 |
+
return [tuple()]
|
| 147 |
+
elif len(start) == 1:
|
| 148 |
+
return [(slice(start[0], end[0] + 1),)]
|
| 149 |
+
|
| 150 |
+
slices = []
|
| 151 |
+
path = []
|
| 152 |
+
|
| 153 |
+
# Dimensions common to start and end can be selected directly
|
| 154 |
+
for s, e in zip(start, end):
|
| 155 |
+
if s == e:
|
| 156 |
+
path.append(slice(s, s + 1))
|
| 157 |
+
else:
|
| 158 |
+
break
|
| 159 |
+
|
| 160 |
+
path = tuple(path)
|
| 161 |
+
divergence_idx = len(path)
|
| 162 |
+
|
| 163 |
+
# start == end, and we're done
|
| 164 |
+
if divergence_idx == len(dims):
|
| 165 |
+
return [tuple(path)]
|
| 166 |
+
|
| 167 |
+
def upper():
|
| 168 |
+
sdi = start[divergence_idx]
|
| 169 |
+
return [
|
| 170 |
+
path + (slice(sdi, sdi + 1),) + s
|
| 171 |
+
for s in _get_minimal_slice_set(
|
| 172 |
+
start[divergence_idx + 1 :],
|
| 173 |
+
[d - 1 for d in dims[divergence_idx + 1 :]],
|
| 174 |
+
dims[divergence_idx + 1 :],
|
| 175 |
+
start_edges=start_edges[divergence_idx + 1 :],
|
| 176 |
+
end_edges=[1 for _ in end_edges[divergence_idx + 1 :]],
|
| 177 |
+
)
|
| 178 |
+
]
|
| 179 |
+
|
| 180 |
+
def lower():
|
| 181 |
+
edi = end[divergence_idx]
|
| 182 |
+
return [
|
| 183 |
+
path + (slice(edi, edi + 1),) + s
|
| 184 |
+
for s in _get_minimal_slice_set(
|
| 185 |
+
[0 for _ in start[divergence_idx + 1 :]],
|
| 186 |
+
end[divergence_idx + 1 :],
|
| 187 |
+
dims[divergence_idx + 1 :],
|
| 188 |
+
start_edges=[1 for _ in start_edges[divergence_idx + 1 :]],
|
| 189 |
+
end_edges=end_edges[divergence_idx + 1 :],
|
| 190 |
+
)
|
| 191 |
+
]
|
| 192 |
+
|
| 193 |
+
# If both start and end are at the edges of the subtree rooted at
|
| 194 |
+
# divergence_idx, we can just select the whole subtree at once
|
| 195 |
+
if start_edges[divergence_idx] and end_edges[divergence_idx]:
|
| 196 |
+
slices.append(path + (slice(start[divergence_idx], end[divergence_idx] + 1),))
|
| 197 |
+
# If just start is at the edge, we can grab almost all of the subtree,
|
| 198 |
+
# treating only the ragged bottom edge as an edge case
|
| 199 |
+
elif start_edges[divergence_idx]:
|
| 200 |
+
slices.append(path + (slice(start[divergence_idx], end[divergence_idx]),))
|
| 201 |
+
slices.extend(lower())
|
| 202 |
+
# Analogous to the previous case, but the top is ragged this time
|
| 203 |
+
elif end_edges[divergence_idx]:
|
| 204 |
+
slices.extend(upper())
|
| 205 |
+
slices.append(
|
| 206 |
+
path + (slice(start[divergence_idx] + 1, end[divergence_idx] + 1),)
|
| 207 |
+
)
|
| 208 |
+
# If both sides of the range are ragged, we need to handle both sides
|
| 209 |
+
# separately. If there's contiguous meat in between them, we can index it
|
| 210 |
+
# in one big chunk
|
| 211 |
+
else:
|
| 212 |
+
slices.extend(upper())
|
| 213 |
+
middle_ground = end[divergence_idx] - start[divergence_idx]
|
| 214 |
+
if middle_ground > 1:
|
| 215 |
+
slices.append(
|
| 216 |
+
path + (slice(start[divergence_idx] + 1, end[divergence_idx]),)
|
| 217 |
+
)
|
| 218 |
+
slices.extend(lower())
|
| 219 |
+
|
| 220 |
+
return [tuple(s) for s in slices]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
@torch.jit.ignore
|
| 224 |
+
def _chunk_slice(
|
| 225 |
+
t: torch.Tensor,
|
| 226 |
+
flat_start: int,
|
| 227 |
+
flat_end: int,
|
| 228 |
+
no_batch_dims: int,
|
| 229 |
+
) -> torch.Tensor:
|
| 230 |
+
"""
|
| 231 |
+
Equivalent to
|
| 232 |
+
|
| 233 |
+
t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end]
|
| 234 |
+
|
| 235 |
+
but without the need for the initial reshape call, which can be
|
| 236 |
+
memory-intensive in certain situations. The only reshape operations
|
| 237 |
+
in this function are performed on sub-tensors that scale with
|
| 238 |
+
(flat_end - flat_start), the chunk size.
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
batch_dims = t.shape[:no_batch_dims]
|
| 242 |
+
start_idx = list(_flat_idx_to_idx(flat_start, batch_dims))
|
| 243 |
+
# _get_minimal_slice_set is inclusive
|
| 244 |
+
end_idx = list(_flat_idx_to_idx(flat_end - 1, batch_dims))
|
| 245 |
+
|
| 246 |
+
# Get an ordered list of slices to perform
|
| 247 |
+
slices = _get_minimal_slice_set(
|
| 248 |
+
start_idx,
|
| 249 |
+
end_idx,
|
| 250 |
+
batch_dims,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
sliced_tensors = [t[s] for s in slices]
|
| 254 |
+
|
| 255 |
+
return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]) for s in sliced_tensors])
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def chunk_layer(
|
| 259 |
+
layer: Callable,
|
| 260 |
+
inputs: Dict[str, Any],
|
| 261 |
+
chunk_size: int,
|
| 262 |
+
no_batch_dims: int,
|
| 263 |
+
low_mem: bool = False,
|
| 264 |
+
_out: Any = None,
|
| 265 |
+
_add_into_out: bool = False,
|
| 266 |
+
) -> Any:
|
| 267 |
+
"""
|
| 268 |
+
Implements the "chunking" procedure described in section 1.11.8.
|
| 269 |
+
|
| 270 |
+
Layer outputs and inputs are assumed to be simple "pytrees,"
|
| 271 |
+
consisting only of (arbitrarily nested) lists, tuples, and dicts with
|
| 272 |
+
torch.Tensor leaves.
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
layer:
|
| 276 |
+
The layer to be applied chunk-wise
|
| 277 |
+
inputs:
|
| 278 |
+
A (non-nested) dictionary of keyworded inputs. All leaves must
|
| 279 |
+
be tensors and must share the same batch dimensions.
|
| 280 |
+
chunk_size:
|
| 281 |
+
The number of sub-batches per chunk. If multiple batch
|
| 282 |
+
dimensions are specified, a "sub-batch" is defined as a single
|
| 283 |
+
indexing of all batch dimensions simultaneously (s.t. the
|
| 284 |
+
number of sub-batches is the product of the batch dimensions).
|
| 285 |
+
no_batch_dims:
|
| 286 |
+
How many of the initial dimensions of each input tensor can
|
| 287 |
+
be considered batch dimensions.
|
| 288 |
+
low_mem:
|
| 289 |
+
Avoids flattening potentially large input tensors. Unnecessary
|
| 290 |
+
in most cases, and is ever so slightly slower than the default
|
| 291 |
+
setting.
|
| 292 |
+
Returns:
|
| 293 |
+
The reassembled output of the layer on the inputs.
|
| 294 |
+
"""
|
| 295 |
+
if not (len(inputs) > 0):
|
| 296 |
+
raise ValueError("Must provide at least one input")
|
| 297 |
+
|
| 298 |
+
initial_dims = [shape[:no_batch_dims] for shape in _fetch_dims(inputs)]
|
| 299 |
+
orig_batch_dims = tuple([max(s) for s in zip(*initial_dims)])
|
| 300 |
+
|
| 301 |
+
def _prep_inputs(t):
|
| 302 |
+
if not low_mem:
|
| 303 |
+
if not sum(t.shape[:no_batch_dims]) == no_batch_dims:
|
| 304 |
+
t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
|
| 305 |
+
t = t.reshape(-1, *t.shape[no_batch_dims:])
|
| 306 |
+
else:
|
| 307 |
+
t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
|
| 308 |
+
return t
|
| 309 |
+
|
| 310 |
+
prepped_inputs = tensor_tree_map(_prep_inputs, inputs)
|
| 311 |
+
prepped_outputs = None
|
| 312 |
+
if _out is not None:
|
| 313 |
+
reshape_fn = lambda t: t.view([-1] + list(t.shape[no_batch_dims:]))
|
| 314 |
+
prepped_outputs = tensor_tree_map(reshape_fn, _out)
|
| 315 |
+
|
| 316 |
+
flat_batch_dim = 1
|
| 317 |
+
for d in orig_batch_dims:
|
| 318 |
+
flat_batch_dim *= d
|
| 319 |
+
|
| 320 |
+
no_chunks = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)
|
| 321 |
+
|
| 322 |
+
i = 0
|
| 323 |
+
out = prepped_outputs
|
| 324 |
+
for _ in range(no_chunks):
|
| 325 |
+
# Chunk the input
|
| 326 |
+
if not low_mem:
|
| 327 |
+
select_chunk = lambda t: t[i : i + chunk_size] if t.shape[0] != 1 else t
|
| 328 |
+
else:
|
| 329 |
+
select_chunk = partial(
|
| 330 |
+
_chunk_slice,
|
| 331 |
+
flat_start=i,
|
| 332 |
+
flat_end=min(flat_batch_dim, i + chunk_size),
|
| 333 |
+
no_batch_dims=len(orig_batch_dims),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
chunks = tensor_tree_map(select_chunk, prepped_inputs)
|
| 337 |
+
|
| 338 |
+
# Run the layer on the chunk
|
| 339 |
+
output_chunk = layer(**chunks)
|
| 340 |
+
|
| 341 |
+
# Allocate space for the output
|
| 342 |
+
if out is None:
|
| 343 |
+
allocate = lambda t: t.new_zeros((flat_batch_dim,) + t.shape[1:])
|
| 344 |
+
out = tensor_tree_map(allocate, output_chunk)
|
| 345 |
+
|
| 346 |
+
# Put the chunk in its pre-allocated space
|
| 347 |
+
out_type = type(output_chunk)
|
| 348 |
+
if out_type is dict:
|
| 349 |
+
|
| 350 |
+
def assign(d1, d2):
|
| 351 |
+
for k, v in d1.items():
|
| 352 |
+
if type(v) is dict:
|
| 353 |
+
assign(v, d2[k])
|
| 354 |
+
else:
|
| 355 |
+
if _add_into_out:
|
| 356 |
+
v[i : i + chunk_size] += d2[k]
|
| 357 |
+
else:
|
| 358 |
+
v[i : i + chunk_size] = d2[k]
|
| 359 |
+
|
| 360 |
+
assign(out, output_chunk)
|
| 361 |
+
elif out_type is tuple:
|
| 362 |
+
for x1, x2 in zip(out, output_chunk):
|
| 363 |
+
if _add_into_out:
|
| 364 |
+
x1[i : i + chunk_size] += x2
|
| 365 |
+
else:
|
| 366 |
+
x1[i : i + chunk_size] = x2
|
| 367 |
+
elif out_type is torch.Tensor:
|
| 368 |
+
if _add_into_out:
|
| 369 |
+
out[i : i + chunk_size] += output_chunk
|
| 370 |
+
else:
|
| 371 |
+
out[i : i + chunk_size] = output_chunk
|
| 372 |
+
else:
|
| 373 |
+
raise ValueError("Not supported")
|
| 374 |
+
|
| 375 |
+
i += chunk_size
|
| 376 |
+
|
| 377 |
+
reshape = lambda t: t.view(orig_batch_dims + t.shape[1:])
|
| 378 |
+
out = tensor_tree_map(reshape, out)
|
| 379 |
+
|
| 380 |
+
return out
|