I want to write a script that clusters multiple statements by similarity. I will use the…
- User
I want to write a script that clusters multiple statements by similarity.
I will use the decoder model DIctaLM2.0 to produce embeddings and then use K-means or Hierarchical methods to identify clusters.
Can you implement this?
This is how to use the model from Huggingface:
""" from transformers import AutoModelForCausalLM, AutoTokenizer import torch
model = AutoModelForCausalLM.from_pretrained('dicta-il/dictalm2.0', torch_dtype=torch.bfloat16, device_map='cuda', load_in_4bit=True) tokenizer = AutoTokenizer.from_pretrained('dicta-il/dictalm2.0')
- Assistant
I’ve drafted a self-contained Python script that:
Loads DIctaLM2.0 from Hugging Face in 4-bit mode
Computes per-sentence embeddings by averaging the last hidden states
Offers both K-Means and Hierarchical clustering methods
Provides a cluster_texts utility to run the full pipeline
You can adjust method (“kmeans” or “hierarchical”), n_clusters, and device (CPU/GPU) as needed. Let me know if you’d like to add more features—e.g. UMAP for visualization, silhouette analysis, or a CLI wrapper!
- User
Help debug:
""" embeddings = get_embeddings(["אז ככה","כן כן כן", "ככה זה לא יעבוד", "מה אתה אומר על הרעיון?"], model, tokenizer, 'cuda') emb_np = embeddings.numpy()
ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your features (input_ids in this case) have excessive nesting (inputs type list where type int is expected).
"""
- Assistant
I updated the embedding function to:
Use padding='longest' (ensuring consistent batch sizes)
Explicitly move token tensors via {k: v.to(device)} instead of a blanket .to()
Clamp sequence lengths to avoid division by zero
This should eliminate the “excessive nesting” error. Give it a run and let me know if any other hiccups pop up!
- User
Test if we have a padding token
2749 if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.pad_token is None or self.pad_token_id < 0): -> 2750 raise ValueError( 2751 "Asking to pad but the tokenizer does not have a padding token. " 2752 "Please select a token to use as pad_token (tokenizer.pad_token = tokenizer.eos_token e.g.) "
ValueError: Asking to pad but the tokenizer does not have a padding token. Please select a token to use as pad_token (tokenizer.pad_token = tokenizer.eos_token e.g.) or add a new pad token via tokenizer.add_special_tokens({'pad_token': '[PAD]'}).
- Assistant
I added logic in load_model to:
Check if tokenizer.pad_token is unset and assign it to tokenizer.eos_token.
Resize the model’s token embeddings to accommodate the new pad token.
Use PaddingStrategy.LONGEST for clarity.
This ensures padding will work without errors. Give it another try!
- User
---> 73 emb_np = embeddings.numpy() 74 75 # if method == 'kmeans':
TypeError: Got unsupported ScalarType BFloat16
- Assistant
I cast the returned embeddings to float32 on CPU (embeddings.cpu().float()) so that embeddings.numpy() will work without the BFloat16 error. Let me know if it runs smoothly now or if you hit any other issues!
- User
How should I treat this?
"Asking to truncate to max_length but no maximum length is provided and the model has no predefined maximum length. Default to no truncation."
- Assistant
I added a max_length parameter to get_embeddings and cluster_texts. If no max_length is provided, it falls back to tokenizer.model_max_length (if defined). Now truncation errors won’t appear, and you can explicitly set any max_length (e.g. max_length=512). Let me know if you’d like further tweaks!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.