Views
No views yet
1import os
2import torch
3import torch.nn as nn
4import torch.nn.functional as F
5
6from tqdm import tqdm
7from transformers import AutoTokenizer, AutoModelForCausalLM
8
9class BottleneckT5Autoencoder:
10 def __init__(self, model_path: str, device='cpu'):
11 self.device = device
12 self.tokenizer = AutoTokenizer.from_pretrained(model_path, model_max_length=512)
13 self.model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).to(self.device)
14 self.model.eval()
15
16 @torch.no_grad()
17 def embed(self, text: str) -> torch.FloatTensor:
18 inputs = self.tokenizer(text, return_tensors='pt').to(self.device)
19 decoder_inputs = self.tokenizer('', return_tensors='pt').to(self.device)
20 return self.model(
21 **inputs,
22 decoder_input_ids=decoder_inputs['input_ids'],
23 encode_only=True,
24 )[0]
25
26 @torch.no_grad()
27 def generate_from_latent(self, latent: torch.FloatTensor, max_length=512, temperature=1.0) -> str:
28 dummy_text = '.'
29 dummy = self.embed(dummy_text)
30 perturb_vector = latent - dummy
31 self.model.perturb_vector = perturb_vector
32 input_ids = self.tokenizer(dummy_text, return_tensors='pt').to(self.device).input_ids
33 output = self.model.generate(
34 input_ids=input_ids,
35 max_length=max_length,
36 do_sample=True,
37 temperature=temperature,
38 top_p=0.9,
39 num_return_sequences=1,
40 )
41 return self.tokenizer.decode(output[0], skip_special_tokens=True)1device = 'cuda' if torch.cuda.is_available() else 'cpu'
2autoencoder = BottleneckT5Autoencoder(model_path='thesephist/contra-bottleneck-t5-large-wikipedia', device=device).embed(text: str) and .generate_from_latent(embedding: torch.FloatTensor).1texts = [
2 'The quick brown fox jumps over the lazy dog',
3 'Hi there! My name is Linus, and I spend a lot of my time thinking about latent spaces of neural network models.',
4 'Notion is a single space where you can think, write, and plan. Capture thoughts, manage projects, or even run an entire company — and do it exactly the way you want.',
5]
6
7for t in texts:
8 embedding = autoencoder.embed(t)
9 reconstruction = autoencoder.generate_from_latent(embedding)
10 print(reconstruction)The quick brown fox jumps over the lazy dog
I'm named after Linus, and I spend a lot of my time thinking about neural networks of latent space models.
Notion is a single place where you can think, plan, and spend time. Capture ideas, manage projects, and even do your own writing — or plan it exactly the way you want.thesephist/contra-bottleneck-t5-large-wikipedia, which strikes a good balance between model size and output quality, but I've trained four variants ranging from 330M to 3B parameters: