{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/T5_encoding_test.ipynb","timestamp":1756468393162},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/T5_encoding_test.ipynb","timestamp":1753784751931},{"file_id":"https://huggingface.co/datasets/codeShare/lora-training-data/blob/main/T5_encoding_test.ipynb","timestamp":1753506570273}],"authorship_tag":"ABX9TyOzkujPFKQx9DIcu1fudilk"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","source":["!pip install transformers"],"metadata":{"id":"Q2jmuaxxF4ev"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @markdown Use the T5 encoder only\n","# Step 2: Import necessary libraries\n","from transformers import T5Tokenizer, T5Model\n","import torch\n","\n","# Step 3: Load the T5 tokenizer and model\n","# You can use 't5-small', 't5-base', 't5-large', etc. 't5-small' is lighter for Colab\n","tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n","model = T5Model.from_pretrained(\"t5-base\")\n","\n","# Step 4: Define the input string\n","input_string = \"Studies have shown that owning a dog is good for you\" # @param {type:'string'}\n","\n","# Step 5: Tokenize the input string to get token IDs\n","input_ids = tokenizer(input_string, return_tensors=\"pt\").input_ids\n","print(\"Token IDs:\", input_ids)\n","\n","# Step 6: (Optional) Get hidden state embeddings\n","# Ensure the model is in evaluation mode\n","model.eval()\n","\n","# Forward pass to get encoder outputs\n","with torch.no_grad():\n"," outputs = model.encoder(input_ids=input_ids)\n"," encoder_hidden_states = outputs.last_hidden_state\n","\n","# Print the shape of the hidden states\n","print(\"Encoder Hidden States Shape:\", encoder_hidden_states.shape)\n","# Example: Shape will be [batch_size, sequence_length, hidden_size], e.g., [1, num_tokens, 768] for t5-base\n","\n","# Step 7: (Optional) Decode token IDs back to text for verification\n","decoded_text = tokenizer.decode(input_ids[0], skip_special_tokens=True)\n","print(\"Decoded Text:\", decoded_text)"],"metadata":{"id":"jT1UmiK8_jHs"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @markdown 🇫🇷 Translate using the T5 model
\n","# @markdown Note: NOT a FLUX feature since FLUX only uses the T5 encoder!\n","\n","# Step 2: Import necessary libraries\n","from transformers import T5Tokenizer, T5ForConditionalGeneration\n","\n","# Step 3: Load the T5 tokenizer and model\n","# Use 't5-base' for balance; 't5-small' for speed, or 't5-large' for better performance\n","tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n","model = T5ForConditionalGeneration.from_pretrained(\"t5-base\")\n","\n","# Step 4: Define the input string with the instruction\n","input_string = \"translate to French: The sun is shining today.\" # @param {type:'string'}\n","\n","# Step 5: Tokenize the input string\n","input_ids = tokenizer(input_string, return_tensors=\"pt\").input_ids\n","\n","# Step 6: Generate the output\n","model.eval()\n","with torch.no_grad():\n"," outputs = model.generate(input_ids, max_length=50)\n"," translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n","\n","# Step 7: Print the result\n","print(\"Translated Text:\", translated_text)\n","\n"],"metadata":{"id":"lovIkU-uDLPn"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# @markdown ⚖️ Compare Similiarity\n","\n","# Step 1: Install required libraries\n","!pip install transformers torch\n","\n","# Step 2: Import necessary libraries\n","from transformers import T5Tokenizer, T5Model\n","import torch\n","import torch.nn.functional as F\n","\n","# Step 3: Load T5 tokenizer and model\n","tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n","model = T5Model.from_pretrained(\"t5-base\")\n","\n","# Step 4: Define input strings\n","text1 = \"a photo The sun is shining today\" # @param {type:'string'}\n","text2 = \"anime screencap The sun is shining today \" # @param {type:'string'}\n","\n","# Step 5: Tokenize the input strings\n","inputs1 = tokenizer(text1, return_tensors=\"pt\", padding=True, truncation=True)\n","inputs2 = tokenizer(text2, return_tensors=\"pt\", padding=True, truncation=True)\n","\n","# Step 6: Get T5 encoder hidden states\n","model.eval()\n","with torch.no_grad():\n"," # Get encoder outputs for both inputs\n"," outputs1 = model.encoder(input_ids=inputs1.input_ids)\n"," outputs2 = model.encoder(input_ids=inputs2.input_ids)\n","\n"," # Extract last hidden states [batch_size, sequence_length, hidden_size]\n"," hidden_states1 = outputs1.last_hidden_state\n"," hidden_states2 = outputs2.last_hidden_state\n","\n","# Step 7: Aggregate hidden states (mean pooling)\n","# Average across the sequence dimension to get a single vector per input\n","embedding1 = hidden_states1.mean(dim=1) # Shape: [1, hidden_size]\n","embedding2 = hidden_states2.mean(dim=1) # Shape: [1, hidden_size]\n","\n","# Step 8: Compute cosine similarity\n","cosine_sim = F.cosine_similarity(embedding1, embedding2, dim=1)\n","print(\"Cosine Similarity:\", cosine_sim.item())\n","\n","# Step 9: (Optional) Print token IDs for reference\n","print(\"Token IDs for text1:\", inputs1.input_ids)\n","print(\"Token IDs for text2:\", inputs2.input_ids)"],"metadata":{"id":"XPymy3EwByMQ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["from transformers import T5Tokenizer, T5Model\n","import torch\n","import torch.nn.functional as F\n","import matplotlib.pyplot as plt\n","import numpy as np\n","\n","# Initialize tokenizer and model\n","tokenizer = T5Tokenizer.from_pretrained(\"t5-base\")\n","model = T5Model.from_pretrained(\"t5-base\")\n","\n","# Provided text\n","text = \"\"\"\n","Minami was expected by his mother to prioritize his acting career over his musical interests. However, he met Haruki Sakura while studying in Northmare, and Haruki became a strong supporter of Minami's dream to become a professional songwriter. Unfortunately, their friendship was strained when they disagreed over Haruki's health, leading Minami to believe that Nagi Rokuya was responsible for Haruki's decision. This disagreement further deepened the complexity of Minami's character and his relationships within the group.\n","\n","In terms of his personal life, Minami celebrates his birthday on June 8 and is currently 19 years old. He is a Gemini, and his height is 174 cm (5' 8\"). Minami's blood type is AB, and his music sign is Senza, which refers to the release pedal in Italian. He is a talented songwriter and plays a crucial role in ZOOL's music production. Minami's dedication to his craft and his ability to connect with others through his fortune-telling skills make him an intriguing and multifaceted character.\n","\n","In his relationships with other characters, Minami has unique dynamics and nicknames. For example, Iori Izumi refers to him as Natsume-san, while Yamato Nikaido simply calls him Natsume. Nagi Rokuya addresses him as Natsume-shi, and Riku Nanase uses the nickname Natsume-san. These nicknames reflect the varying levels of familiarity and closeness between Minami and his fellow group members.\n","\n","The etymology of Minami's name is also worth noting. His surname, Natsume, can mean \"Chinese date\" or \"tea ceremony\" in Japanese. The given name Minami consists of the characters \"mi,\" which means snake or serpent, and \"nami,\" which translates to waves or breakers. These meanings add depth to Minami's character and may provide insight into his personality and journey.\n","\n","Kotaro Nishiyama, the voice actor who brings Minami to life, has shared his thoughts on portraying the character. Nishiyama expressed that he found Minami to be a unique and twisted character, different from any he had played before. He enjoyed the experience of bringing Minami's complex personality to the screen and hopes that viewers will look forward to seeing how ZOOL's aggressive nature clashes with the world of Idolish7.\n","\n","In terms of trivia, Minami possesses some interesting quirks and hobbies. He is ambidextrous and tends to drink with his left hand. Minami attended Northmarea to study music and songwriting, which led to his role as ZOOL's songwriter. He has a passion for playing the piano, although he had to give up lessons and a piano contest due to his busy acting career. Interestingly, Minami dislikes rabbits because he was once bitten by one as a child. He also collects watches and clocks as a hobby, showcasing his appreciation for timepieces.\n","\n","Overall, Minami Natsume is a complex and intriguing character in the world of Idolish7. His past as a child acting prodigy, his role as ZOOL's songwriter, and his unique talents in fortune-telling make him a captivating presence within the group. With his composed demeanor and hidden darkness, Minami adds depth and complexity to the narrative of Idolish7.\n","\n","Index 4925: Hisho and what are her abilities and role in the anime series Cyber Team in Akihabara Hisho is a female character in the series Cyber Team in Akihabara. She is the loyal secretary and assistant to Washuu Ryuugasaki. Hisho first appears in Episode 06, where she accompanies Washuu as he assigns the three girls a home economics assignment to make curry.\n","\n","In Chapter 6, Hisho is by Washuu's side as he gives the girls permission to work on their curry assignment. After leaving Akihabara Junior High School, Hisho hands Washuu his cellphone as he receives a call from the mayor of Akihabara regarding the school's payments.\n","\n","Later in Chapter 11, Hisho agrees to help Takashi dress up Hibari in a red and pink gown. She takes Hibari to a room filled with dresses for her to choose from.\n","\n","In Chapter 21, Hisho is seen inside a secret facility with Washuu and Cigogne. Washuu uses his staff to create a purple light that transforms Hisho into Diva Hakuya, along with her own diva army. Washuu gives Hisho the task of dealing with Hibari and the group. Hisho and her diva army confront the girls, but they are ultimately defeated. However, Hisho manages to retreat with her army by teleportation. In the end of the episode, she and her diva armies corner Hibari, shooting her with rapid fire. Hibari survives due to being infused with Densuke.\n","\n","In Chapter 23, Hisho and her diva army corner both Tsubame and Hibari. However, most of her army is decapitated by Jun, Miyama, and Hatoko using the apostolus cannon given to them by Takashi. Hisho and her diva armies then summon a deadly christening light in a purple glow, intending to eliminate everyone. Hibari manages to escape their line of defense despite her injuries.\n","\n","Towards the end of Chapter 24, Hisho engages in a hand-to-hand combat with Tsubame. They are evenly matched, but when Washuu dies of old age, Hisho senses his fall and decides to join him. She allows herself to be slashed by Tsubame in her advanced diva state, falling to the ground in an explosion.\n","\n","Hisho has short layered dark green hair with a distinctive curly spike on each side of her hair. She has brown eyes and wears yellow ochre earrings. As Washuu's secretary, she wears a gray corporate business suit with a yellow ribbon as her collar, a matching gray corporate business skirt, and black high heels. In Chapter 11, her suit changes to green.\n","\n","When transformed into Diva Hakuya, Hisho wears a dark red armored leotard under a black turtleneck suit. She also wears dark red and yellow brown shoulder pauldrons, gloves, and thigh-high boots. Her helmet is dark red with a brown face protector, and she has two long straight brown horns on each side. She also has white butterfly wings on her back.\n","\n","In terms of fighting capacity, Hisho demonstrates her skills in Chapter 21 when she and her diva army shoot the divas with rapid fire. She can defeat most divas with a single blow using telepathic force. However, she is ultimately defeated by Hibari in her advanced diva state, with the left side of her face protector breaking into small pieces. Hisho also calls for reinforcements from her master after four of her army members are defeated. She and her diva armies engage in rapid fire against Hibari, but she is knocked down and falls to Earth.\n","\n","In Chapter 23, Hisho and her army manage to take down both Hibari and Tsubame in their advanced diva states. Her fight with Tsubame is evenly matched, especially when Tsubame taps into her human emotions. Hisho also summons a purple glow along with her diva army to create a deadly christening light, but Hibari manages to escape their attack in her injured state.\n","\n","Index 4926: plot of the Agatha Christie's Marple episode \"A Murder is Announced\" (specifically for this adaptation) \"A Murder is Announced\" is the fourth episode of the first series of \"Agatha Christie's Marple\". It was directed by John Strickland and written by Stewart Harcourt. The episode aired on ITV by Granada Television on 2 January 2005. It is an adaptation of Agatha Christie's novel of the same name.\n","\n","The episode begins with the residents of Chipping Cleghorn being astonished by an advertisement in the local newspaper, announcing that a murder will take place the following Friday at 7:30 p.m. at Little Paddocks, the home of Letitia Blacklock. A group gathers at the specified time, but suddenly the lights go out and a young hotel employee named Rudi Schertz is shot. The police initially believe that Rudi had placed the ad and planned it as a robbery. However, Miss Marple, the astute detective, suspects that the killer is one of the people in the room. As two more people present during the murder are subsequently killed, Miss Marple takes it upon herself to unravel a complex web of relationships and false identities, all centered around the wealthy industrialist Randall Goedler, who had died ten years earlier.\n","\n","In comparison to the original story, there are several differences in the episode. The vicar and his wife, who Miss Marple stays with in the novel, are not present in the episode. Instead, Miss Marple stays with Miss Murgatroyd, the daughter of an old friend. The absence of certain characters, such as Diana Harmon and Mrs. Easterbrook, also alters the dynamics of the story. Additionally, the character of Laura Easterbrook is not present, and the love story between Edmund and Philippa has been eliminated. The episode also introduces new elements, such as the characters Hinch and Murgatroyd being portrayed as two young lesbian women. Inspector Craddock is portrayed as more impatient and aggressive, and the episode ends with the death of Belle Goedler, which did not occur in the novel.\n","\n","The cast of \"A Murder is Announced\" includes Geraldine McEwan as Miss Marple, Christian Coulson as Edmund Swettenham, Cherie Lunghi as Sadie Swettenham, Robert Pugh as Colonel Easterbrook, Keeley Hawes as Phillipa Haymes, Zoë Wanamaker as Letitia Blacklock, Claire Skinner as Amy Murgatroyd, Frances Barber as Lizzie Hinchcliffe, Elaine Paige as Dora Bunner, Matthew Goode as Patrick Simmons, Sienna Guillory as Julia Simmons, Catherine Tate as Mitzi Kosinski, and many others.\n","\n","The episode features various tropes and themes commonly found in murder mysteries, such as the victim knowing a dark secret, the murderer pretending to be the intended victim, the lights going out before the murder, and the witnesses being intentionally misled.\n","\n","Filming locations for \"A Murder is Announced\" include Debenham House in Holland Park, London for the interior scenes of the Royal Spa Hotel, Chilworth Manor in Guildford, Surrey for Little Paddocks, Dorchester Abbey in Dorchester on Thames for the Chipping Cleghorn parish church, and Eilean Donan Castle in Kyle of Lochalsh, Scotland for exterior shots.\n","\n","Overall, \"A Murder is Announced\" is a gripping episode of \"Agatha Christie's Marple\" that showcases the brilliant detective skills of Miss Marple as she unravels a complex murder mystery.\n","\"\"\"\n","\n","# Tokenize and truncate to 500 tokens\n","inputs = tokenizer(text, return_tensors=\"pt\", padding=True, truncation=True, max_length=500)\n","text_tokens = inputs.input_ids[0][:500] # Ensure exactly 500 tokens\n","encoded_text = tokenizer.decode(text_tokens, skip_special_tokens=True)\n","\n","print(\"Encoded text (first 500 tokens):\", encoded_text)"],"metadata":{"id":"ncWamlakquBD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Reference NSFW phrase\n","nsfw_phrase = \"nsfw , girl , nipples poking out , partially visible vulva , implied nudity beneath tight bodysuit\"\n","\n","# Insert NSFW phrase at the beginning\n","modified_text = nsfw_phrase + \" \" + encoded_text\n","\n","# Re-tokenize to ensure 500 tokens\n","modified_inputs = tokenizer(modified_text, return_tensors=\"pt\", padding=True, truncation=True, max_length=500)\n","modified_tokens = modified_inputs.input_ids[0][:500]\n","modified_text_encoded = tokenizer.decode(modified_tokens, skip_special_tokens=True)\n","\n","print(\"Modified text with NSFW phrase:\", modified_text_encoded)"],"metadata":{"id":"4ho0fYTIqvXS"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Tokenize the NSFW phrase\n","nsfw_inputs = tokenizer(nsfw_phrase, return_tensors=\"pt\", padding=True, truncation=True)\n","nsfw_tokens = nsfw_inputs.input_ids\n","\n","# Get embedding for NSFW phrase\n","model.eval()\n","with torch.no_grad():\n"," nsfw_outputs = model.encoder(input_ids=nsfw_inputs.input_ids)\n"," nsfw_embedding = nsfw_outputs.last_hidden_state.mean(dim=1) # Mean pooling\n","\n","# Initialize similarity scores\n","window_size = nsfw_inputs.input_ids.size(1) # Size of NSFW phrase in tokens\n","similarities = []\n","positions = []\n","\n","# Slide window across modified text\n","for i in range(0, min(500 - window_size + 1, modified_tokens.size(0) - window_size + 1)):\n"," window_tokens = modified_tokens[i:i + window_size].unsqueeze(0)\n"," with torch.no_grad():\n"," window_outputs = model.encoder(input_ids=window_tokens)\n"," window_embedding = window_outputs.last_hidden_state.mean(dim=1)\n"," similarity = F.cosine_similarity(nsfw_embedding, window_embedding, dim=1).item()\n"," similarities.append(similarity * 100) # Convert to percentage\n"," positions.append(i)\n","\n","# If the text is shorter than expected, pad with zeros\n","while len(positions) < 500:\n"," similarities.append(0.0)\n"," positions.append(len(positions))"],"metadata":{"id":"8TY9NgB4q7cR"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["# Plotting\n","plt.figure(figsize=(10, 6))\n","plt.plot(positions, similarities, label='Cosine Similarity (%)')\n","plt.xlabel('Token Position')\n","plt.ylabel('Similarity (%)')\n","plt.title('Similarity of NSFW Phrase vs. Text Across Positions')\n","plt.grid(True)\n","plt.legend()\n","plt.show()"],"metadata":{"id":"jYURlsI_q9CG"},"execution_count":null,"outputs":[]}]}