deepsparse.py 3.22 KB
Newer Older
mgoin's avatar
mgoin committed
1
2
3
from typing import List, Optional, Tuple, Union
from tqdm import tqdm
import random
4
5
import numpy
import torch
mgoin's avatar
mgoin committed
6

Michael Goin's avatar
Michael Goin committed
7
import deepsparse
mgoin's avatar
mgoin committed
8
9

from lm_eval import utils
Michael Goin's avatar
Michael Goin committed
10
11
12
13
from lm_eval.base import BaseLM


class DeepSparseLM(BaseLM):
14
    # Default max sequence length setting for when no `max_length` is provided
Michael Goin's avatar
Michael Goin committed
15
16
17
18
19
20
21
22
23
24
25
    _DEFAULT_MAX_LENGTH = 2048

    def __init__(
        self,
        pretrained: str,
        tokenizer: Optional[str] = None,
        batch_size: Optional[Union[int, str]] = 1,
        max_gen_toks: Optional[int] = 256,
        max_length: Optional[int] = None,
        trust_remote_code: Optional[bool] = False,
    ):
26
27
28
29
        """
        Wrapper around the DeepSparse pipeline to make it compatible with the
        llm-evaluation-harness.
        """
Michael Goin's avatar
Michael Goin committed
30
31
        super().__init__()

32
33
34
35
        self._batch_size = int(batch_size)
        self._max_length = max_length or self._DEFAULT_MAX_LENGTH
        self._max_gen_toks = max_gen_toks

Michael Goin's avatar
Michael Goin committed
36
        # Initialize new model and tokenizer instances
37
        self.model = deepsparse.TextGeneration(
Michael Goin's avatar
Michael Goin committed
38
            model_path=pretrained,
39
            sequence_length=self._max_length,
Michael Goin's avatar
Michael Goin committed
40
41
42
43
44
45
46
            trust_remote_code=trust_remote_code,
            batch_size=batch_size,
        )
        self.tokenizer = tokenizer if tokenizer else self.model.tokenizer

        self.vocab_size = self.tokenizer.vocab_size

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    def _model_call(self, inps) -> torch.Tensor:
        """
        Override the _model_call method to use the DeepSparse pipeline for
        logits generation.

        inps: a torch tensor of shape [batch, sequence]
        the size of sequence may vary from call to call
        returns: a torch tensor of shape [batch, sequence, vocab] with the
        logits returned from the model
        """
        # Encode the tokens to strings
        prompt = self.model.tokenizer.batch_decode(inps.numpy())

        # Run the model to map the prompt to logits
        out = self.model(
            prompt=prompt,
            max_new_tokens=0,
            include_prompt_logits=True,
            output_scores=True,
        )
        logits_numpy = numpy.stack([generation.score for generation in out.generations])
        return torch.from_numpy(logits_numpy)

    def _model_generate(self, context, max_length, eos_token_id):
        # Encode the prompt tokens to strings
        prompt = self.tokenizer.batch_decode(context.numpy())

        # Run generation
        out = self.model(
            prompt=prompt, max_new_tokens=max_length, force_max_tokens=True
        )
        # Return tokens for prompt + generated text
        return numpy.array(
            [self.tokenizer(prompt[0] + out.generations[0].text)["input_ids"]]
        )

Michael Goin's avatar
Michael Goin committed
83
84

    @property
mgoin's avatar
mgoin committed
85
86
87
88
89
    def eot_token(self) -> str:
        return self.tokenizer.eos_token

    @property
    def eot_token_id(self) -> int:
Michael Goin's avatar
Michael Goin committed
90
91
92
93
        return self.tokenizer.eos_token_id

    @property
    def max_length(self):
94
        return self._max_length
Michael Goin's avatar
Michael Goin committed
95
96
97
98
99
100
101
102
103
104
105

    @property
    def max_gen_toks(self):
        return self._max_gen_toks

    @property
    def batch_size(self):
        return self._batch_size

    @property
    def device(self):
106
        pass
Michael Goin's avatar
Michael Goin committed
107
108

    def tok_encode(self, string: str):
109
        return self.tokenizer.encode(string)
Michael Goin's avatar
Michael Goin committed
110
111
112
113

    def tok_decode(self, tokens):
        return self.tokenizer.decode(tokens)