-
Notifications
You must be signed in to change notification settings - Fork 77
/
rwkv_cpp_model.py
204 lines (164 loc) · 7.1 KB
/
rwkv_cpp_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import os
import torch
import multiprocessing
import rwkv_cpp_shared_library
from typing import Tuple, Optional, List
class RWKVModel:
"""
PyTorch wrapper around rwkv.cpp model.
"""
def __init__(
self,
shared_library: rwkv_cpp_shared_library.RWKVSharedLibrary,
model_path: str,
thread_count: int = max(1, multiprocessing.cpu_count() // 2),
gpu_layer_count: int = 0,
**kwargs
):
"""
Loads the model and prepares it for inference.
In case of any error, this method will throw an exception.
Parameters
----------
shared_library : RWKVSharedLibrary
rwkv.cpp shared library.
model_path : str
Path to RWKV model file in ggml format.
thread_count : int
Thread count to use. If not set, defaults to CPU count / 2.
gpu_layer_count : int
Count of layers to offload onto the GPU, must be >= 0.
"""
if 'gpu_layers_count' in kwargs:
gpu_layer_count = kwargs['gpu_layers_count']
assert os.path.isfile(model_path), f'{model_path} is not a file'
assert thread_count > 0, 'Thread count must be > 0'
assert gpu_layer_count >= 0, 'GPU layer count must be >= 0'
self._library = shared_library
self._ctx = self._library.rwkv_init_from_file(model_path, thread_count)
if gpu_layer_count > 0:
self._library.rwkv_gpu_offload_layers(self._ctx, gpu_layer_count)
self._state_buffer_element_count = self._library.rwkv_get_state_buffer_element_count(self._ctx)
self._logits_buffer_element_count = self._library.rwkv_get_logits_buffer_element_count(self._ctx)
self._valid = True
@property
def n_vocab(self):
return self._library.rwkv_get_n_vocab(self._ctx)
@property
def n_embed(self):
return self._library.rwkv_get_n_embed(self._ctx)
@property
def n_layer(self):
return self._library.rwkv_get_n_layer(self._ctx)
def eval(
self,
token: int,
state_in: Optional[torch.Tensor],
state_out: Optional[torch.Tensor] = None,
logits_out: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Evaluates the model for a single token.
In case of any error, this method will throw an exception.
Parameters
----------
token : int
Index of next token to be seen by the model. Must be in range 0 <= token < n_vocab.
state_in : Optional[torch.Tensor]
State from previous call of this method. If this is a first pass, set it to None.
state_out : Optional[torch.Tensor]
Optional output tensor for state. If provided, must be of type float32, contiguous and of shape (state_buffer_element_count).
logits_out : Optional[torch.Tensor]
Optional output tensor for logits. If provided, must be of type float32, contiguous and of shape (logits_buffer_element_count).
Returns
-------
logits, state
Logits vector of shape (n_vocab); state for the next step.
"""
assert self._valid, 'Model was freed'
if state_in is not None:
validate_tensor(state_in, 'state_in', self._state_buffer_element_count)
state_in_ptr = state_in.data_ptr()
else:
state_in_ptr = 0
if state_out is not None:
validate_tensor(state_out, 'state_out', self._state_buffer_element_count)
else:
state_out = torch.zeros(self._state_buffer_element_count, dtype=torch.float32, device='cpu')
if logits_out is not None:
validate_tensor(logits_out, 'logits_out', self._logits_buffer_element_count)
else:
logits_out = torch.zeros(self._logits_buffer_element_count, dtype=torch.float32, device='cpu')
self._library.rwkv_eval(
self._ctx,
token,
state_in_ptr,
state_out.data_ptr(),
logits_out.data_ptr()
)
return logits_out, state_out
def eval_sequence(
self,
tokens: List[int],
state_in: Optional[torch.Tensor],
state_out: Optional[torch.Tensor] = None,
logits_out: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Evaluates the model for a sequence of tokens.
In case of any error, this method will throw an exception.
Parameters
----------
tokens : List[int]
Indices of the next tokens to be seen by the model. Must be in range 0 <= token < n_vocab.
state_in : Optional[torch.Tensor]
State from previous call of this method. If this is a first pass, set it to None.
state_out : Optional[torch.Tensor]
Optional output tensor for state. If provided, must be of type float32, contiguous and of shape (state_buffer_element_count).
logits_out : Optional[torch.Tensor]
Optional output tensor for logits. If provided, must be of type float32, contiguous and of shape (logits_buffer_element_count).
Returns
-------
logits, state
Logits vector of shape (n_vocab); state for the next step.
"""
assert self._valid, 'Model was freed'
if state_in is not None:
validate_tensor(state_in, 'state_in', self._state_buffer_element_count)
state_in_ptr = state_in.data_ptr()
else:
state_in_ptr = 0
if state_out is not None:
validate_tensor(state_out, 'state_out', self._state_buffer_element_count)
else:
state_out = torch.zeros(self._state_buffer_element_count, dtype=torch.float32, device='cpu')
if logits_out is not None:
validate_tensor(logits_out, 'logits_out', self._logits_buffer_element_count)
else:
logits_out = torch.zeros(self._logits_buffer_element_count, dtype=torch.float32, device='cpu')
self._library.rwkv_eval_sequence(
self._ctx,
tokens,
state_in_ptr,
state_out.data_ptr(),
logits_out.data_ptr()
)
return logits_out, state_out
def free(self):
"""
Frees all allocated resources.
In case of any error, this method will throw an exception.
The object must not be used anymore after calling this method.
"""
assert self._valid, 'Already freed'
self._valid = False
self._library.rwkv_free(self._ctx)
def __del__(self):
# Free the context on GC in case user forgot to call free() explicitly.
if hasattr(self, '_valid') and self._valid:
self.free()
def validate_tensor(buf: torch.Tensor, name: str, size: int) -> None:
assert buf.device == torch.device('cpu'), f'{name} is not on CPU'
assert buf.dtype == torch.float32, f'{name} is not of type float32'
assert buf.shape == (size,), f'{name} has invalid shape {buf.shape}, expected ({size})'
assert buf.is_contiguous(), f'{name} is not contiguous'