Views
No views yet
1from transformers import AutoModel, AutoTokenizer
2
3tokenizer = AutoTokenizer.from_pretrained("rrivera1849/LUAR-MUD")
4model = AutoModel.from_pretrained("rrivera1849/LUAR-MUD")
5
6# we embed `episodes`, a colletion of documents presumed to come from an author
7# NOTE: make sure that `episode_length` consistent across `episode`
8batch_size = 3
9episode_length = 16
10text = [
11 ["Foo"] * episode_length,
12 ["Bar"] * episode_length,
13 ["Zoo"] * episode_length,
14]
15text = [j for i in text for j in i]
16tokenized_text = tokenizer(
17 text,
18 max_length=32,
19 padding="max_length",
20 truncation=True,
21 return_tensors="pt"
22)
23# inputs size: (batch_size, episode_length, max_token_length)
24tokenized_text["input_ids"] = tokenized_text["input_ids"].reshape(batch_size, episode_length, -1)
25tokenized_text["attention_mask"] = tokenized_text["attention_mask"].reshape(batch_size, episode_length, -1)
26print(tokenized_text["input_ids"].size()) # torch.Size([3, 16, 32])
27print(tokenized_text["attention_mask"].size()) # torch.Size([3, 16, 32])
28
29out = model(**tokenized_text)
30print(out.size()) # torch.Size([3, 512])
31
32# to get the Transformer attentions:
33out, attentions = model(**tokenized_text, output_attentions=True)
34print(attentions[0].size()) # torch.Size([48, 12, 32, 32])1
2import numpy as np
3import torch
4from termcolor import cprint
5from transformers import AutoModel, AutoTokenizer
6from tqdm import tqdm
7
8def generate_data(num_batches: int = 100, batch_size: int = 32, num_samples_per_author: int = 16):
9 """
10 Generator that produces dummy data for testing.
11
12 Args:
13 num_batches (int): Total number of batches to yield.
14 batch_size (int): Number of authors per batch.
15 num_samples_per_author (int): Number of text samples per author.
16
17 Yields:
18 list: A batch of data structured as a list of lists of strings.
19 Shape: (batch_size, num_samples_per_author)
20 """
21 s = "This is an example string."
22 for batch in tqdm(range(num_batches)):
23 # Create a batch where each element is a list of 's' repeated 'num_samples_per_author' times
24 yield [[s] * num_samples_per_author for _ in range(batch_size)]
25
26def flatten(l):
27 """
28 Helper function to flatten a 2D list into a 1D list.
29
30 Args:
31 l (list): List of lists.
32
33 Returns:
34 list: Flattened list.
35 """
36 return [item for sublist in l for item in sublist]
37
38def main():
39 cprint("Starting LUAR-MUD example script...", 'magenta')
40
41 # --- Model Loading ---
42 cprint("Loading model 'rrivera1849/LUAR-MUD'...", 'blue')
43 # trust_remote_code=True is required for custom model architectures like LUAR-MUD
44 model = AutoModel.from_pretrained("rrivera1849/LUAR-MUD", trust_remote_code=True)
45
46 model.eval()
47
48 # Check for CUDA availability and move model to appropriate device
49 device = "cuda" if torch.cuda.is_available() else "cpu"
50 cprint(f"Moving model to device: {device}", 'yellow')
51 model.to(device)
52
53 # --- Tokenizer Loading ---
54 cprint("Loading tokenizer...", 'blue')
55 tokenizer = AutoTokenizer.from_pretrained("rrivera1849/LUAR-MUD", trust_remote_code=True)
56
57 # --- Configuration ---
58 num_batches = 100
59 batch_size = 32
60 num_samples_per_author = 16
61 max_length = 512
62
63 cprint("\nConfiguration:", 'cyan')
64 print(f" Batch Size: {batch_size}")
65 print(f" Samples per Author: {num_samples_per_author}")
66 print(f" Max Length: {max_length}")
67 print(f" Device: {device}\n")
68
69 all_outputs = []
70
71 cprint("Starting inference loop...", 'green')
72
73 # context manager for disabling gradient calculation to save memory/compute
74 with torch.inference_mode():
75 for i, batch in enumerate(generate_data(num_batches=num_batches, batch_size=batch_size, num_samples_per_author=num_samples_per_author)):
76 if (i + 1) % 10 == 0:
77 print(f" Processing batch {i + 1}...")
78
79 # Flatten the batch structure for tokenization:
80 # (batch_size, num_samples) -> (batch_size * num_samples)
81 batch = flatten(batch)
82
83 # Tokenize the flattened batch
84 inputs = tokenizer(batch, return_tensors="pt", padding=True, max_length=max_length, truncation=True)
85
86 # Move inputs to the same device as the model
87 inputs = inputs.to(device)
88
89 # Reshape input_ids and attention_mask to match the model's expected 3D input:
90 # (batch_size, num_samples_per_author, sequence_length)
91 inputs["input_ids"] = inputs["input_ids"].reshape(batch_size, num_samples_per_author, -1)
92 inputs["attention_mask"] = inputs["attention_mask"].reshape(batch_size, num_samples_per_author, -1)
93
94 # Forward pass through the model
95 outputs = model(**inputs)
96
97 # Move outputs back to CPU and convert to numpy for storage
98 all_outputs.append(outputs.cpu().numpy())
99
100 # Concatenate all batch results into a single array
101 # axis=0 corresponds to the batch dimension
102 all_outputs = np.concatenate(all_outputs, axis=0)
103
104 cprint("\nInference complete!", 'green')
105 cprint(f"Final output shape: {all_outputs.shape}", attrs=['bold'])
106
107if __name__ == "__main__":
108 main()@inproceedings{uar-emnlp2021,
author = {Rafael A. Rivera Soto and Olivia Miano and Juanita Ordonez and Barry Chen and Aleem Khan and Marcus Bishop and Nicholas Andrews},
title = {Learning Universal Authorship Representations},
booktitle = {EMNLP},
year = {2021},
}