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

Function get_random_span

language/capwap/utils/text_utils.py:182–239  ·  view source on GitHub ↗

Get random subspan from text token sequence, following heuristics. Heuristics: 1) Should not start or end mid-wordpiece. 2) Must contain at least one non-stopword token. 3) Length should be drawn from Geo(p) and less than max_span_len. Args: text: [], space-separated t

(text, p, max_span_len, max_iter=10)

Source from the content-addressed store, hash-verified

180
181
182def get_random_span(text, p, max_span_len, max_iter=10):
183 """Get random subspan from text token sequence, following heuristics.
184
185 Heuristics:
186 1) Should not start or end mid-wordpiece.
187 2) Must contain at least one non-stopword token.
188 3) Length should be drawn from Geo(p) and less than max_span_len.
189
190 Args:
191 text: <string> [], space-separated token string.
192 p: <float32> Geometric distribution parameter.
193 max_span_len: Length to pad or truncate to.
194 max_iter: Maximum rejection sampling iterations.
195
196 Returns:
197 span_wid: <string>
198 """
199 # Split text into tokens.
200 tokens = tf.string_split([text]).values
201 seq_len = tf.size(tokens)
202
203 def reject(start, end):
204 """Reject span sample."""
205 span = tokens[start:end + 1]
206 wordpiece_boundary = tf.logical_or(
207 tf.strings.regex_full_match(span[0], r"^##.*"),
208 tf.strings.regex_full_match(span[-1], r"^##.*"))
209 span = tokens[start:end]
210 stopwords = list(nltk_utils.get_stopwords() | set(string.punctuation))
211 non_stopword = tf.setdiff1d(span, stopwords)
212 all_stopword = tf.equal(tf.size(non_stopword.out), 0)
213 length = tf.equal(tf.size(span), 0)
214 return tf.reduce_any([wordpiece_boundary, all_stopword, length])
215
216 def sample(start, end):
217 """Sample length from truncated Geo(p)."""
218 # Sample from truncated geometric distribution.
219 geometric = lambda k: (1 - p)**(k - 1) * p
220 probs = np.array([geometric(k) for k in range(1, max_span_len + 1)])
221 probs /= probs.sum()
222 length = tf.distributions.Categorical(probs=probs).sample() + 1
223
224 # Sample start uniformly.
225 max_offset = tf.maximum(1, seq_len - length + 1)
226 start = tf.random.uniform([], 0, max_offset, dtype=tf.int32)
227 end = start + length
228
229 # Return span.
230 return [start, end]
231
232 # Rejection sample. Start with dummy span variable.
233 start = tf.constant(0)
234 end = tf.constant(0)
235 start, end = tf.while_loop(
236 reject, sample, [start, end], maximum_iterations=max_iter)
237 span = tf.strings.reduce_join(tokens[start:end], separator=" ")
238
239 return span

Callers

nothing calls this directly

Calls 2

constantMethod · 0.80
sizeMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…