MCPcopy Create free account
hub / github.com/Turing-Project/WriteGPT / _top_k_sample

Function _top_k_sample

LanguageNetwork/GPT2/train/modeling.py:376–407  ·  view source on GitHub ↗

Does top-k sampling. if ignore_ids is on, then we will zero out those logits. :param logits: [batch_size, vocab_size] tensor :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict, like padding maybe :param

(logits, ignore_ids=None, num_samples=1, k=10)

Source from the content-addressed store, hash-verified

374
375
376def _top_k_sample(logits, ignore_ids=None, num_samples=1, k=10):
377 """
378 Does top-k sampling. if ignore_ids is on, then we will zero out those logits.
379 :param logits: [batch_size, vocab_size] tensor
380 :param ignore_ids: [vocab_size] one-hot representation of the indices we'd like to ignore and never predict,
381 like padding maybe
382 :param p: topp threshold to use, either a float or a [batch_size] vector
383 :return: [batch_size, num_samples] samples
384 # TODO FIGURE OUT HOW TO DO THIS ON TPUS. IT'S HELLA SLOW RIGHT NOW, DUE TO ARGSORT I THINK
385 """
386 with tf.variable_scope('top_p_sample'):
387 batch_size, vocab_size = get_shape_list(logits, expected_rank=2)
388
389 probs = tf.nn.softmax(logits if ignore_ids is None else logits - tf.cast(ignore_ids[None], tf.float32) * 1e10,
390 axis=-1)
391 # [batch_size, vocab_perm]
392 indices = tf.argsort(probs, direction='DESCENDING')
393
394 # find the top pth index to cut off. careful we don't want to cutoff everything!
395 # result will be [batch_size, vocab_perm]
396 k_expanded = k if isinstance(k, int) else k[:, None]
397 exclude_mask = tf.range(vocab_size)[None] >= k_expanded
398
399 # OPTION A - sample in the sorted space, then unsort.
400 logits_to_use = tf.batch_gather(logits, indices) - tf.cast(exclude_mask, tf.float32) * 1e10
401 sample_perm = tf.random.categorical(logits=logits_to_use, num_samples=num_samples)
402 sample = tf.batch_gather(indices, sample_perm)
403
404 return {
405 'probs': probs,
406 'sample': sample,
407 }
408
409
410class GroverModel(object):

Callers 1

sample_stepFunction · 0.70

Calls 1

get_shape_listFunction · 0.90

Tested by

no test coverage detected