Download embedings.py from hunterfiras/model_1: direct link, hf CLI and curl.
- Browser
- Download file 2.38 kB
-
https://huggingface.co/hunterfiras/model_1/resolve/main/embedings.py
- Command line
-
hf download hf://hunterfiras/model_1/embedings.py
-
curl -L -o embedings.py https://huggingface.co/hunterfiras/model_1/resolve/main/embedings.py
2.38 kB
| try: | |
| import cupy as np | |
| except: | |
| import numpy as np | |
| import pickle | |
| import BPE_training as BPE | |
| class RoPE: | |
| def __init__(self,d,seq_len=None,pos=None): | |
| """ Rotatory positional embeding | |
| it rotates each pair of dimensions in the vector by an angle=pos * theta to give it position information | |
| theta=10000**(-2*i/d) i is the dimention pair number and d is the last dimention of the input matrix | |
| """ | |
| self.d=d | |
| if pos is None: | |
| pos=np.arange(seq_len).reshape(-1,1) | |
| else: | |
| pos=np.array([pos]).reshape(1,1) | |
| i=np.arange(d//2) | |
| theta=10000**(-2*i/d) | |
| angles=pos * theta | |
| self.cos_=np.repeat(np.cos(angles),2,axis=1) | |
| self.sin_=np.repeat(np.sin(angles),2,axis=1) | |
| def rotate_half(self,X): | |
| res=np.zeros((X.shape)) | |
| res[:,:,:,1::2]=X[:,:,:,::2] | |
| res[:,:,:,::2]=X[:,:,:,1::2]*-1 | |
| return res | |
| def __call__(self,X): | |
| return (X*self.cos_ + self.rotate_half(X)*self.sin_) | |
| def backward(self,dRotated): | |
| """ | |
| As RoPE rotates the input matrix's pairs of dimensions by theta[dims_pair] | |
| RoPE(X)=R@X so the derivative of it is the function rotating it by the opposit angle so basically its RoPE with -theta | |
| """ | |
| return (dRotated*self.cos_ - self.rotate_half(dRotated)*self.sin_) | |
| class lookup: | |
| def __init__(self,We): | |
| self.ET=We | |
| def __call__(self,tokens): | |
| return self.ET[tokens] | |
| def backward(self,dE,tokens): | |
| dmodel=dE.shape[-1] | |
| dwe=np.zeros_like(self.ET) | |
| try: | |
| np.add.at(dwe,tokens.ravel(),dE.reshape(-1,dmodel)) | |
| except: | |
| import cupyx | |
| cupyx.scatter_add(dwe,tokens.ravel(),dE.reshape(-1,dmodel)) | |
| return dwe | |
| class embeding_data: | |
| def __init__(self,save_path,saved=True,data_path=None,merges=None): | |
| if not saved: | |
| self.tokens=self.save_embeds(data_path,save_path,merges) | |
| else: | |
| self.tokens=self.load_embeds(save_path) | |
| def save_embeds(self,data_path,save_path,merges): | |
| with open(data_path,"r") as file: | |
| text=file.read() | |
| tokens=BPE.encoder(text,merges) | |
| pickle.dump(tokens,open(save_path,"bw")) | |
| def load_embeds(self,save_path): | |
| return pickle.load(open(save_path,"br")) | |