Python equivalent of C++ Arithmetic Encoder. Strictly emulates 32-bit unsigned overflow for high/low.
(cdf, input_sym, output_buffer, output_lengths)
| 2221 | |
| 2222 | |
| 2223 | def encode_fast_new(cdf, input_sym, output_buffer, output_lengths): |
| 2224 | """ |
| 2225 | Python equivalent of C++ Arithmetic Encoder. |
| 2226 | Strictly emulates 32-bit unsigned overflow for high/low. |
| 2227 | """ |
| 2228 | cdf_np = cdf.cpu().numpy().view(np.uint16).astype(np.uint32) |
| 2229 | sym_np = input_sym.cpu().numpy().astype(np.uint8) |
| 2230 | |
| 2231 | n_layers, n_tokens, n_channels = sym_np.shape |
| 2232 | out_buf_np = np.zeros(output_buffer.shape, dtype=np.uint8) |
| 2233 | out_len_np = np.zeros(output_lengths.shape, dtype=np.int32) |
| 2234 | |
| 2235 | def encode_one(args): |
| 2236 | layer_idx, c = args |
| 2237 | length = _encode_single_channel( |
| 2238 | cdf_np[layer_idx, c], |
| 2239 | sym_np[layer_idx, :, c], |
| 2240 | out_buf_np[layer_idx, c], |
| 2241 | ) |
| 2242 | out_len_np[layer_idx, c] = length |
| 2243 | |
| 2244 | tasks = [(layer_idx, c) for layer_idx in range(n_layers) for c in range(n_channels)] |
| 2245 | |
| 2246 | with ThreadPoolExecutor() as executor: |
| 2247 | list(executor.map(encode_one, tasks)) |
| 2248 | |
| 2249 | output_buffer.copy_(torch.from_numpy(out_buf_np)) |
| 2250 | output_lengths.copy_(torch.from_numpy(out_len_np)) |
| 2251 | |
| 2252 | |
| 2253 | @njit(cache=True) |