Meliad wrapper for LM inference.
| 34 | |
| 35 | |
| 36 | class LanguageModelInference: |
| 37 | """Meliad wrapper for LM inference.""" |
| 38 | |
| 39 | def __init__(self, vocab_path: str, load_dir: str, mode='beam_search'): |
| 40 | self.vocab = t5.data.SentencePieceVocabulary(vocab_path) |
| 41 | |
| 42 | # This task won't be pulling from a dataset. |
| 43 | def null_iter_fn() -> None: |
| 44 | return None |
| 45 | |
| 46 | process_summaries_f = inference_utils.models.process_summaries_function( |
| 47 | self.vocab |
| 48 | ) |
| 49 | |
| 50 | trainer = inference_utils.training_loop.Trainer( |
| 51 | get_training_dataset_iterator=null_iter_fn, |
| 52 | get_test_dataset_iterator=None, |
| 53 | pretty_print_input_function=None, |
| 54 | process_summaries_function=process_summaries_f, |
| 55 | load_dir=load_dir, |
| 56 | workdir='', # Don't log or save checkpoints. |
| 57 | replicate_mode=False, |
| 58 | ) # Run on a single device at batch size 1. |
| 59 | self.trainer = trainer |
| 60 | |
| 61 | # Create and initialize the model. |
| 62 | (tstate, _, imodel, prngs) = trainer.initialize_model() |
| 63 | self.imodel = imodel |
| 64 | self.batch_size = imodel.task_config.batch_size |
| 65 | |
| 66 | self.n = imodel.num_heads |
| 67 | self.h = imodel.head_size |
| 68 | |
| 69 | # Create an inference task. |
| 70 | writers = {} |
| 71 | self.task = trainer.create_training_task(mode, imodel, prngs, writers) # pylint: disable=too-many-function-args |
| 72 | |
| 73 | # Register any additional actions. |
| 74 | # Actions are cleared first for use with colab. |
| 75 | inference_utils.training_loop.clear_interstep_callbacks() |
| 76 | inference_utils.training_loop.register_interstep_callbacks() |
| 77 | self.tstate = tstate |
| 78 | |
| 79 | # some default parameters. |
| 80 | eos = [0] * 1024 |
| 81 | for idx in self.encode_list(['.', ';']): |
| 82 | eos[idx] = 1 |
| 83 | |
| 84 | self.eos = np.array(eos, dtype=np.bfloat16) |
| 85 | self.mask = jax.numpy.ones([1024], dtype=np.bfloat16) |
| 86 | |
| 87 | def decode(self, ids: list[int]) -> str: |
| 88 | return self.vocab.decode(ids) |
| 89 | |
| 90 | def decode_list(self, tokens: list[int]) -> list[str]: |
| 91 | return [self.decode([tok]) for tok in tokens] |
| 92 | |
| 93 | def encode(self, inputs_str: str) -> list[int]: |
nothing calls this directly
no outgoing calls
no test coverage detected