Text Classification
Transformers
Safetensors
English
emcoder
emotion-recognition
bayesian-deep-learning
mc-dropout
uncertainty-quantification
multi-label-classification
custom_code
Eval Results (legacy)
Instructions to use yezdata/EmCoder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use yezdata/EmCoder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="yezdata/EmCoder", trust_remote_code=True)# Load model directly from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained("yezdata/EmCoder", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
File size: 9,352 Bytes
a10898b | 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | from __future__ import annotations
from math import pi, log
import torch
from torch.amp import autocast
from torch.nn import Module
from torch import nn, broadcast_tensors, is_tensor, tensor, Tensor
from typing import Literal
def exists(val):
return val is not None
def default(val, d):
return val if exists(val) else d
def broadcat(tensors, dim=-1):
broadcasted_tensors = broadcast_tensors(*tensors)
return torch.cat(broadcasted_tensors, dim=dim)
def slice_at_dim(t, dim_slice: slice, *, dim):
dim += (t.ndim if dim < 0 else 0)
colons = [slice(None)] * t.ndim
colons[dim] = dim_slice
return t[tuple(colons)]
def rotate_half(x):
orig_shape = x.shape
d_head = orig_shape[-1]
x = x.view(*orig_shape[:-1], d_head // 2, 2)
x1 = x[..., 0]
x2 = x[..., 1]
res = torch.stack((-x2, x1), dim=-1)
return res.view(*orig_shape)
@autocast('cuda', enabled=False)
def apply_rotary_emb(
freqs,
t,
start_index=0,
scale=1.,
seq_dim=-2,
freqs_seq_dim=None
):
dtype = t.dtype
if not exists(freqs_seq_dim):
if freqs.ndim == 2 or t.ndim == 3:
freqs_seq_dim = 0
if t.ndim == 3 or exists(freqs_seq_dim):
seq_len = t.shape[seq_dim]
freqs = slice_at_dim(freqs, slice(-seq_len, None), dim=freqs_seq_dim)
rot_dim = freqs.shape[-1]
end_index = start_index + rot_dim
assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}'
t_left = t[..., :start_index]
t_middle = t[..., start_index:end_index]
t_right = t[..., end_index:]
t_transformed = (t_middle * freqs.cos() * scale) + (rotate_half(t_middle) * freqs.sin() * scale)
out = torch.cat((t_left, t_transformed, t_right), dim=-1)
return out.type(dtype)
def apply_learned_rotations(rotations, t, start_index=0, freq_ranges=None):
if exists(freq_ranges):
rotations = torch.einsum('..., f -> ... f', rotations, freq_ranges)
rotations = rotations.reshape(*rotations.shape[:-2], -1)
rotations = rotations.repeat_interleave(2, dim=-1)
return apply_rotary_emb(rotations, t, start_index=start_index)
class RotaryEmbedding(Module):
def __init__(
self,
dim,
custom_freqs: Tensor | None = None,
freqs_for: Literal['lang', 'pixel', 'constant'] = 'lang',
theta = 10000,
max_freq = 10,
num_freqs = 1,
learned_freq = False,
use_xpos = False,
xpos_scale_base = 512,
interpolate_factor = 1.,
theta_rescale_factor = 1.,
seq_before_head_dim = False,
cache_if_possible = True,
cache_max_seq_len = 8192
):
super().__init__()
theta *= theta_rescale_factor ** (dim / (dim - 2))
self.freqs_for = freqs_for
if exists(custom_freqs):
freqs = custom_freqs
elif freqs_for == 'lang':
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
elif freqs_for == 'pixel':
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
elif freqs_for == 'constant':
freqs = torch.ones(num_freqs).float()
self.cache_if_possible = cache_if_possible
self.cache_max_seq_len = cache_max_seq_len
self.register_buffer('cached_freqs', torch.zeros(cache_max_seq_len, dim), persistent=False)
self.cached_freqs_seq_len = 0
self.freqs = nn.Parameter(freqs, requires_grad=learned_freq)
self.learned_freq = learned_freq
self.register_buffer('dummy', torch.tensor(0), persistent=False)
self.seq_before_head_dim = seq_before_head_dim
self.default_seq_dim = -3 if seq_before_head_dim else -2
assert interpolate_factor >= 1.
self.interpolate_factor = interpolate_factor
self.use_xpos = use_xpos
if not use_xpos:
return
scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim)
self.scale_base = xpos_scale_base
self.register_buffer('scale', scale, persistent=False)
self.register_buffer('cached_scales', torch.zeros(cache_max_seq_len, dim), persistent=False)
self.cached_scales_seq_len = 0
self.apply_rotary_emb = staticmethod(apply_rotary_emb)
@property
def device(self):
return self.dummy.device
def get_seq_pos(self, seq_len, device=None, dtype=None, offset=0):
device = default(device, self.device)
dtype = default(dtype, self.cached_freqs.dtype)
return (torch.arange(seq_len, device=device, dtype=dtype) + offset) / self.interpolate_factor
def rotate_queries_or_keys(self, t, seq_dim=None, offset=0, scale=None):
seq_dim = default(seq_dim, self.default_seq_dim)
assert not self.use_xpos or exists(scale), 'you must use `.rotate_queries_and_keys` method instead'
device, dtype, seq_len = t.device, t.dtype, t.shape[seq_dim]
seq = self.get_seq_pos(seq_len, device=device, dtype=dtype, offset=offset)
freqs = self.forward(seq, seq_len=seq_len, offset=offset)
if seq_dim == -3:
freqs = freqs.unsqueeze(1)
return apply_rotary_emb(freqs, t, scale=default(scale, 1.), seq_dim=seq_dim)
def rotate_queries_with_cached_keys(self, q, k, seq_dim=None, offset=0):
dtype, device, seq_dim = q.dtype, q.device, default(seq_dim, self.default_seq_dim)
q_len, k_len = q.shape[seq_dim], k.shape[seq_dim]
assert q_len <= k_len
q_scale = k_scale = 1.
if self.use_xpos:
seq = self.get_seq_pos(k_len, dtype=dtype, device=device)
q_scale = self.get_scale(seq[-q_len:]).type(dtype)
k_scale = self.get_scale(seq).type(dtype)
rotated_q = self.rotate_queries_or_keys(q, seq_dim=seq_dim, scale=q_scale, offset=k_len - q_len + offset)
rotated_k = self.rotate_queries_or_keys(k, seq_dim=seq_dim, scale=k_scale ** -1)
return rotated_q.type(q.dtype), rotated_k.type(k.dtype)
def rotate_queries_and_keys(self, q, k, seq_dim=None):
seq_dim = default(seq_dim, self.default_seq_dim)
assert self.use_xpos
device, dtype, seq_len = q.device, q.dtype, q.shape[seq_dim]
seq = self.get_seq_pos(seq_len, dtype=dtype, device=device)
freqs = self.forward(seq, seq_len=seq_len)
scale = self.get_scale(seq, seq_len=seq_len).to(dtype)
if seq_dim == -3:
freqs = freqs.unsqueeze(1)
scale = scale.unsqueeze(1)
rotated_q = apply_rotary_emb(freqs, q, scale=scale, seq_dim=seq_dim)
rotated_k = apply_rotary_emb(freqs, k, scale=scale ** -1, seq_dim=seq_dim)
return rotated_q.type(q.dtype), rotated_k.type(k.dtype)
def get_scale(self, t: Tensor, seq_len: int | None = None, offset=0):
assert self.use_xpos
should_cache = self.cache_if_possible and exists(seq_len) and (offset + seq_len) <= self.cache_max_seq_len
if should_cache and (seq_len + offset) <= self.cached_scales_seq_len:
return self.cached_scales[offset:(offset + seq_len)]
scale = 1.
if self.use_xpos:
power = (t - len(t) // 2) / self.scale_base
scale = self.scale ** power.unsqueeze(-1)
scale = scale.repeat_interleave(2, dim=-1)
if should_cache and offset == 0:
self.cached_scales[:seq_len] = scale.detach()
self.cached_scales_seq_len = seq_len
return scale
def get_axial_freqs(self, *dims, offsets: tuple[int | float, ...] | Tensor | None = None):
Colon = slice(None)
all_freqs = []
if exists(offsets):
if not is_tensor(offsets):
offsets = tensor(offsets)
assert len(offsets) == len(dims)
for ind, dim in enumerate(dims):
offset = 0
if exists(offsets):
offset = offsets[ind]
if self.freqs_for == 'pixel':
pos = torch.linspace(-1, 1, steps=dim, device=self.device)
else:
pos = torch.arange(dim, device=self.device)
pos = pos + offset
freqs = self.forward(pos, seq_len=dim)
all_axis = [None] * len(dims)
all_axis[ind] = Colon
new_axis_slice = (Ellipsis, *all_axis, Colon)
all_freqs.append(freqs[new_axis_slice])
all_freqs = broadcast_tensors(*all_freqs)
return torch.cat(all_freqs, dim=-1)
@autocast('cuda', enabled=False)
def forward(self, t: Tensor, seq_len: int | None = None, offset=0):
should_cache = (
self.cache_if_possible and not self.learned_freq and
exists(seq_len) and self.freqs_for != 'pixel' and
(offset + seq_len) <= self.cache_max_seq_len
)
if should_cache and (offset + seq_len) <= self.cached_freqs_seq_len:
return self.cached_freqs[offset:(offset + seq_len)].detach()
freqs = self.freqs
freqs = torch.einsum('..., f -> ... f', t.type(freqs.dtype), freqs)
freqs = freqs.repeat_interleave(2, dim=-1)
if should_cache and offset == 0:
self.cached_freqs[:seq_len] = freqs.detach()
self.cached_freqs_seq_len = seq_len
return freqs |