(self, num_decodes, vocab_size, blank_id, logits_modifier)
| 565 | logits_modifier=[top_k_logits(1), config_for_function(top_k_logits).set(k=1)], |
| 566 | ) |
| 567 | def test_greedy_decode(self, num_decodes, vocab_size, blank_id, logits_modifier): |
| 568 | cfg: CTCDecoderModel.Config = CTCDecoderModel.default_config().set( |
| 569 | input_dim=6, |
| 570 | vocab_size=vocab_size, |
| 571 | blank_id=blank_id, |
| 572 | ) |
| 573 | |
| 574 | # Initialize layer parameters. |
| 575 | layer: CTCDecoderModel = cfg.set(name="test").instantiate(parent=None) |
| 576 | prng_key = jax.random.PRNGKey(123) |
| 577 | decode_key, predict_key, init_key, input_key = jax.random.split(prng_key, num=4) |
| 578 | layer_params = layer.initialize_parameters_recursively(init_key) |
| 579 | |
| 580 | batch_size, max_seq_len = 4, 10 |
| 581 | seq_len = jnp.array([10, 7, 5, 8]) |
| 582 | # [batch_size, max_seq_len, dim]. |
| 583 | inputs = jax.random.normal(input_key, [batch_size, max_seq_len, cfg.input_dim]) * 1000 |
| 584 | # [batch_size, max_seq_len]. |
| 585 | paddings = jnp.arange(max_seq_len) >= seq_len[:, None] |
| 586 | |
| 587 | @functools.partial(jax.jit, static_argnames=("method", "modify_logits", "num_decodes")) |
| 588 | def jit_method(inputs, prng_key, method, modify_logits=False, num_decodes=None): |
| 589 | if modify_logits and logits_modifier is not None: |
| 590 | inputs["logits_modifier"] = logits_modifier |
| 591 | if num_decodes is not None: |
| 592 | inputs["num_decodes"] = num_decodes |
| 593 | outputs, _ = F( |
| 594 | layer, |
| 595 | inputs=inputs, |
| 596 | is_training=True, |
| 597 | prng_key=prng_key, |
| 598 | state=layer_params, |
| 599 | method=method, |
| 600 | ) |
| 601 | return outputs |
| 602 | |
| 603 | sample_decode_outputs: DecodeOutputs = jit_method( |
| 604 | dict(input_batch=dict(inputs=inputs, paddings=paddings)), |
| 605 | prng_key=decode_key, |
| 606 | method="sample_decode", |
| 607 | modify_logits=True, |
| 608 | num_decodes=num_decodes, |
| 609 | ) |
| 610 | |
| 611 | greedy_decode_outputs: DecodeOutputs = jit_method( |
| 612 | dict(input_batch=dict(inputs=inputs, paddings=paddings)), |
| 613 | prng_key=decode_key, |
| 614 | method="greedy_decode", |
| 615 | ) |
| 616 | |
| 617 | # Should be equivalent to taking the top logit of each output. |
| 618 | # [batch_size, max_seq_len, vocab_size]. |
| 619 | logits = jit_method( |
| 620 | dict(input_batch=dict(inputs=inputs, paddings=paddings)), |
| 621 | prng_key=predict_key, |
| 622 | method="predict", |
| 623 | ) |
| 624 | log_probs = jax.nn.log_softmax(logits, axis=-1) |
nothing calls this directly
no test coverage detected