MCPcopy Create free account
hub / github.com/apple/axlearn / _gather_beams

Function _gather_beams

axlearn/common/decoding.py:78–120  ·  view source on GitHub ↗

Gathers the beam slices indexed by beam_indices into new beam array. Args: nested: NestedTensor or scalars (the latter ignored). beam_indices: Array of beam_indices. batch_size: Size of batch. old_beam_size: Size of _old_ beam dimension. new_beam_size: Si

(
    nested: NestedTensor,
    beam_indices: Tensor,
    batch_size: int,
    old_beam_size: int,
    new_beam_size: int,
    one_hot: bool = True,
)

Source from the content-addressed store, hash-verified

76
77
78def _gather_beams(
79 nested: NestedTensor,
80 beam_indices: Tensor,
81 batch_size: int,
82 old_beam_size: int,
83 new_beam_size: int,
84 one_hot: bool = True,
85) -> Tensor:
86 """Gathers the beam slices indexed by beam_indices into new beam array.
87
88 Args:
89 nested: NestedTensor or scalars (the latter ignored).
90 beam_indices: Array of beam_indices.
91 batch_size: Size of batch.
92 old_beam_size: Size of _old_ beam dimension.
93 new_beam_size: Size of _new_ beam dimension.
94 one_hot: Whether to perform gathers by one-hot contraction or directly.
95
96 Returns:
97 New beam arrays
98 [batch_size, old_beam_size, ...] --> [batch_size, new_beam_size, ...].
99
100 TODO(sneha): The method does a likely O(n) copy to track history,
101 could use a tree / single parent pointer instead.
102 Check with timeit after.
103 """
104 if one_hot:
105 # Gather via one-hot contraction, needed for SPMD partitioning.
106 oh_beam_indices = jax.nn.one_hot(beam_indices, old_beam_size, dtype=jnp.int32)
107
108 def gather_fn(x):
109 return jnp.einsum("bno,bo...->bn...", oh_beam_indices, x).astype(x.dtype)
110
111 else:
112 # True gather via fancy indexing.
113 batch_indices = jnp.reshape(
114 jnp.arange(batch_size * new_beam_size) // new_beam_size, (batch_size, new_beam_size)
115 )
116
117 def gather_fn(x):
118 return x[batch_indices, beam_indices]
119
120 return vectorized_tree_map(lambda x: gather_fn(x) if x.ndim > 1 else x, nested)
121
122
123def _top_k_two_stage(x: Tensor, k: int):

Callers 2

_gather_topk_beamsFunction · 0.85
beam_search_loop_body_fnFunction · 0.85

Calls 2

vectorized_tree_mapFunction · 0.90
gather_fnFunction · 0.85

Tested by

no test coverage detected