MCPcopy Create free account
hub / github.com/google-research/language / gather

Function gather

language/capwap/utils/tensor_utils.py:125–164  ·  view source on GitHub ↗

A partial implementation of PyTorch gather, for dim=1. Given a src tensor of variable size, this function gathers multiple elements along the 2nd dimension (dim=1), for every batch in the 1st dimension (dim=0). Args: src: [batch_size, d_1, ..., d_n] indices: [batch_size,

(src, indices)

Source from the content-addressed store, hash-verified

123
124
125def gather(src, indices):
126 """A partial implementation of PyTorch gather, for dim=1.
127
128 Given a src tensor of variable size, this function gathers multiple elements
129 along the 2nd dimension (dim=1), for every batch in the 1st dimension (dim=0).
130
131 Args:
132 src: <T> [batch_size, d_1, ..., d_n]
133 indices: <int32> [batch_size, num_indices]
134
135 Returns:
136 output: <T> [batch_size, num_indices, d_2, ..., d_n]
137 """
138 # Hereby begins the painful dance of tf.gather_nd.
139 batch_size = shape(indices, 0)
140 num_indices = shape(indices, 1)
141
142 # [batch_size, 1]
143 batch_idx = tf.reshape(tf.range(batch_size), [batch_size, 1])
144
145 # [batch_size, num_indices]
146 batch_idx = tf.tile(batch_idx, [1, num_indices])
147
148 # [batch_size * num_indices]
149 batch_idx = tf.reshape(batch_idx, [-1])
150
151 # [batch_size * num_indices]
152 flat_indices = tf.reshape(indices, [-1])
153
154 # [batch_size * num_indices, 2]
155 idx = tf.stack([batch_idx, flat_indices], 1)
156
157 # [batch_size * num_indices, d_2, ..., d_n]
158 output = tf.gather_nd(src, idx)
159
160 # [batch_size, num_indices, d_2, ..., d_n]
161 output = tf.reshape(output, [batch_size, num_indices] +
162 [shape(output, i) for i in range(1, len(output.shape))])
163
164 return output

Callers

nothing calls this directly

Calls 1

shapeFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…