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!
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!
User
Any advice?
----> 5 clusters = cluster_texts(samples, method='kmeans', n_clusters=k, device='cuda')
6 # save a pickle and a text file of the results
7 with open(f'clusters_{k}.pkl', 'wb') as f:
6 frames
/usr/local/lib/python3.11/dist-packages/transformers/tokenization_utils_fast.py in set_truncation_and_padding(self, padding_strategy, truncation_strategy, max_length, stride, pad_to_multiple_of, padding_side)
492
493 if current != target:
--> 494 self._tokenizer.enable_truncation(**target)
495
496 if padding_strategy == PaddingStrategy.DO_NOT_PAD:
OverflowError: int too big to convert
Assistant
The root of that overflow is that when you call:
pythonCopyEditmax_length = getattr(tokenizer, 'model_max_length', None)
sometimes the HF‐loader will set model_max_length to an absurdly large placeholder (or even 2**63–1), and then later when the fast tokenizer tries to “enable_truncation(… max_length=huge_int …)”, Python chokes on converting that huge Python int into a C int.
A few simple fixes:
Explicitly pick a sane max length.
Rather than relying on tokenizer.model_max_length, just pass in something like max_length=512 (or 256, or whatever you know your texts will fit under).
pythonCopyEditclusters = cluster_texts(samples, max_length=512, …)
Clamp the tokenizer’s built-in max length.
After loading the tokenizer, you can override:
pythonCopyEdittokenizer.model_max_length = min(tokenizer.model_max_length, 512)
That way any downstream calls to enable_truncation will use at most 512.
Guard against absurd values in code.
In your get_embeddings, before you put max_length into tokenize_kwargs, do something like:
pythonCopyEditif max_length is None or max_length > 10_000:
max_length = 512
That ensures you never pass a too-big integer to the fast tokenizer.
TL;DR: don’t let the tokenizer’s placeholder model_max_length run wild—either hard‐code a reasonable max_length, or clamp/override tokenizer.model_max_length to something like 512.
User
----> 5 clusters = cluster_texts(samples, max_length=512, method='kmeans', n_clusters=k, device='cuda')
6 # save a pickle and a text file of the results
7 with open(f'clusters_{k}.pkl', 'wb') as f:
OutOfMemoryError: CUDA out of memory. Tried to allocate 22.00 MiB. GPU 0 has a total capacity of 14.74 GiB of which 16.12 MiB is free. Process 95772 has 14.72 GiB memory in use. Of the allocated memory 14.52 GiB is allocated by PyTorch, and 77.72 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management
Assistant
I added:
Batching (batch_size param) to split your texts into smaller groups and free GPU memory between batches.
A clamp on max_length to avoid huge truncation values.
torch.cuda.empty_cache() after each batch to reduce fragmentation.
Now you can tune batch_size (e.g. 2–8) based on your GPU. This should prevent OOM errors. Let me know how it goes!
User
/usr/local/lib/python3.11/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning:
The secret HF_TOKEN does not exist in your Colab secrets.
To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.
You will be able to reuse this secret in all of your notebooks.
Please note that authentication is recommended but still optional to access public models or datasets.
warnings.warn(
tokenizer_config.json: 100%
932/932 [00:00<00:00, 103kB/s]
tokenizer.model: 100%
513k/513k [00:01<00:00, 98.0kB/s]
tokenizer.json:
1.86M/? [00:00<00:00, 59.9MB/s]
special_tokens_map.json: 100%
414/414 [00:00<00:00, 53.8kB/s]
config.json: 100%
625/625 [00:00<00:00, 77.0kB/s]
model.safetensors.index.json:
23.9k/? [00:00<00:00, 2.17MB/s]
Fetching 3 files: 100%
3/3 [01:18<00:00, 78.91s/it]
model-00002-of-00003.safetensors: 100%
5.00G/5.00G [00:57<00:00, 126MB/s]
model-00003-of-00003.safetensors: 100%
4.55G/4.55G [00:58<00:00, 181MB/s]
model-00001-of-00003.safetensors: 100%
4.95G/4.95G [01:18<00:00, 377MB/s]
Loading checkpoint shards: 100%
3/3 [00:17<00:00, 6.27s/it]
generation_config.json: 100%
403/403 [00:00<00:00, 49.7kB/s]
Cluster 2:
שלום , מה הדעות שלכם ?
האם הדעה שלך זהה גם על המצב אז ? מה ההבדל ?
למה הסקתה שדיברתי על המצב כיום ?
זה נראה לי יותר הגיוני לפי העמדה שלך ושלא התיחסת לטענות חזקות של הצד השני שיכולות להיות מוצגות על זמן מלחמת השפות
עכשיו אתה מסיק סתם על הדעה שלי .
זה נראה לי כבר עניין של ערכים
Cluster 0:
אני בעד שימוש בשפה מייצגת כיוון שיש לה יתרונות רבים כמו תקשורת עם שאר העולם בתחומים רבים כמו לימודים .
בשביל להתקדם בעולם בעיקר בעולם האקדמי צרי לכתוב בשפה בינלאומית כדי שכל העולם יוכל להבין אותך .
הדיון שלנו כפול בכך שהמצב שונה היום ובתקופת מלחמת השפות ,
כיום הרבה מהמידע גם באינטרנט וגם בעיתונים או ספרים כתוב בשפות שונות כך שלימודי שפה עוזרים לנו בחקר ובהבנה של נושאים .
לדעתי המצב כיום שונה מהצב אז בכך שהעברית ״ השתכללה ״ וכוללת הרבה יותר מילים , יחד עם כך שהטכנולוגיה מכפה על פער התקשורת שנוצר משימוש בשפות שונות .
למרות זאת , עדיין שימוש בשפה המייצגת יוסיף לתקשורת וההבנה .
כיום הרבה מהמידע באינטרנט , בעיתונים ובספרים כתוב בשפות שונות , כך שלימודי שפה ששונה מעברית יכול לתרום בחקר של נושאים .
אם נגיע למצב בעתיד , שהטכנולוגיה מחפה על הפער התקשורתי בין השפות ( סוג של גוגל טרנסלייט סופר מתקדם ) , עדיין היית בוחרת בשפה המייצגת ? )
אין לי בעיה בשימוש בשפות זרות בשביל לימודים בימינו , כל עוד התלמידים מרגישים בנוח ללמוד בשפה וזה משרת את טובת הכלל .
אך מדברים פה על שימוש ספציפי במוסדות לימודים , ובתקופה כמו פעם שהתרגום האינטרניטי ולקסיקון השפה העברית היו דלים , בכדי ללמוד בצורה מיטבית הייתי בוחר בשפה המייצגת .
Assistant
I’ve added:
Offloading support (offload_folder, offload_state_dict=True) so weights spill to disk instead of GPU.
Attention slicing & gradient checkpointing to cut down peak memory.
Lowered default batch_size to 4 (and suggestion to go down to 1).
Advice in docstrings: you can also switch to device='cpu' if GPU still OOMs.
Try this configuration, and let me know whether it fits your GPU constraints!
עד כמה השימוש בשפות זרות בבתי לימודים גבוהים עלול ״ להשפיע ״ על גיבוש הלאום ?
אבל נוסף על כך חשוב שתהיה את האופציה ללמוד אנגלית ( או שפה אחרת ) ברמה גבוהה , כך שאם יש אנשים שמעוניינים להמשיך לאוניברסיטה אחרי התיכון , הם יכולים לעשות את זה .
לימודי שפה זרה הם כמו אנגלית למשל , פותחים בפנינו דלת לתקשורת עם אנשים ולחיפוש מידע .
אך כיום כאשר מתרכזים בלימודים גבוהים לדעתי עדיף להשתמש בשפה מייצגת בשביל תקשורת ונגישות לאנשים מכל העולם .
את חושבת שאת כל המקצועות צריך ללמוד בשפה מייצגת כמו אנגלית לדוגמא ?
Cluster 3:
אני מסכימה ,
אני מסכימה איתכם .
אני מסכימה איתכם .
אתה לא מסכים איתי ?
אני מסכימה .
טוב ,
אני גם חושבת .
Cluster 1:
למה אתה ( עברי ) מעדיף להשתמש בעברית ?
אבל לפני הקמת המדינה הייתה לדעתי חשיבות רבה לשימוש בשפה העברית לתחיית הלאום היהודי .
בתקופה אז , שעוד לא הייתה מדינה באופן רשמי והעם היהודי רק התחיל להתארגן במושבות ובמוסדות חינוכיים , הייתה חשיבות גדולה לשימוש בשפה העברית .
אפשר לראות מהמקור כמה היה חשוב אז לבסס את השפה כשולטת בארץ .
היום , שיש מדינה ומוסדות חינוך מסודרים ליהודים , גם שימוש בשפות זרות יכול לתרום .
אני מסכים שהשפה העברית מהווה גורם מקשר גדולל ללאום ושימוש בה חשוב .
פחות עניין של ערכים , יותר עניין של יחס ביניהם .
לדעתי לימוד בעברית חשוב , אם כבר זה רק בבית ספר .
אלו שירצו להיעזר בשפה יכולים ואלו שלא , לא חייבים .
בעבר לחזק את השפה העברית בתור השפה של העם .
העולים החדשים הגיעו כאשר כל אחד מהם מדבר בשפה כך ששימוש בשפה אחת מרכזית היה דבר נחוץ וחשו למדינה .
Loading checkpoint shards: 100%
3/3 [00:06<00:00, 1.90s/it]
WARNING:accelerate.big_modeling:Some parameters are on the meta device because they were offloaded to the cpu.
OutOfMemoryError Traceback (most recent call last)
/tmp/ipython-input-176-884-7421.py in <cell line: 0>()
3 # repeat the pipeline for multiple k's
4 for k in range(4, 9):
----> 5 clusters = cluster_texts(samples, max_length=512, method='kmeans', n_clusters=k, device='cuda')
6 # save a pickle and a text file of the results
7 with open(f'clusters_{k}.pkl', 'wb') as f:
OutOfMemoryError: CUDA out of memory. Tried to allocate 172.00 MiB. GPU 0 has a total capacity of 22.16 GiB of which 157.38 MiB is free. Process 3310 has 22.00 GiB memory in use. Of the allocated memory 21.51 GiB is allocated by PyTorch, and 276.32 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)