/var/spool/slurmd/job27790692/slurm_script: line 9: 649648 Killed python preprocess.py cat > sout_preprocess.txt
slurmstepd: error: Detected 1 oom-kill event(s) in StepId=27790692.batch cgroup. Some of your processes may have been killed by the cgroup out-of-memory handler.
def preprocess_text_segments(df: pd.DataFrame, max_words: int) -> pd.DataFrame:
"""
Divide the text into segments of approx max_words words each.
Make sure to not split sentences.
Add a column "segment_id" to the dataframe to identify each segment.
The ids should be in the format <testimony_id>_<segment_number>.
1. If a testimony has less than max_words, it should have a single segment with segment_number 0.
2. If a testimony has more than max_words, it should be split into multiple segments, each with segment_number starting from 0.
"""
all_segments = []
# Get sentences
print("Loading SpaCy model...")
if spacy.prefer_gpu():
print("Using GPU")
else:
print("Using CPU")
# spacy.require_gpu()
start = time.time()
nlp = spacy.load("he_ner_news_trf", disable=["tagger", "parser", "ner"]) # Requires GPU for best performance
print(f"Model loaded in {(time.time() - start):.2f} seconds\n")
print("Segmenting sentences...")
print()
for idx, row in df.iterrows():
identifier = row['Identifier']
testimony_id = identifier.split(".")[-1] if pd.notna(identifier) else str(random.randint(100000, 999999))
# process only this testimony
sentences = segment_hebrew_spacy(row['text'], nlp=nlp)
segment = ""
segment_word_count = 0
segment_number = 0
for sent in sentences:
sent_word_count = len(sent.split())
if segment_word_count + sent_word_count > max_words:
all_segments.append({
**row.to_dict(), # keep metadata
# 'testimony_id': testimony_id,
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
})
segment_number += 1
segment = sent
segment_word_count = sent_word_count
else:
segment = f"{segment} {sent}".strip()
segment_word_count += sent_word_count
if segment:
all_segments.append({
**row.to_dict(), # keep metadata
# 'testimony_id': testimony_id,
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
})
# save progressively
res = pd.DataFrame(all_segments)
res.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
print(f"Processed testimony {identifier} into {segment_number + 1} segments.")
# clear memory
del res
gc.collect()
minutes = int((time.time() - start) / 60)
print(f"Segmentation done in {minutes} minutes")
res = pd.DataFrame(all_segments)
# set index to tid_order
res.set_index('tid_order', inplace=True)
return res
Assistant
User
How should I change this?
def segment_hebrew_spacy(text, nlp):
doc = nlp(text)
return [sent.text for sent in doc.sents]
Assistant
Right now, your segment_hebrew_spacy function calls nlp(text) on the entire testimony at once. If a testimony is very long, this creates a huge transformer graph in GPU memory, which is probably what’s causing the OOM.
You can fix this by processing in smaller batches using nlp.pipe or by splitting the text into paragraphs/chunks first. Here’s a safer approach:
Option 1: Process text in chunks (safer for GPU)
pythonCopy codedef segment_hebrew_spacy(text, nlp, chunk_size=1000):
"""
Split text into smaller chunks of ~chunk_size words and segment sentences.
Returns a list of sentences.
"""
words = text.split()
sentences = []
User
Assistant
Ah! The error is here:
pythonCopy codesentences = segment_hebrew_spacy_texts([row['text']], nlp=nlp)
Your segment_hebrew_spacy_texts function returns a list of lists:
pythonCopy code# example
segment_hebrew_spacy_texts(["some text"], nlp)
=> [["sentence 1", "sentence 2", ...]]
So sentences is actually:
pythonCopy code[ ["sentence 1", "sentence 2", ...] ] # list containing one list
Then here:
pythonCopy codefor sent in sentences:
sent_word_count = len(sent.split()) # ❌ sent is a list, not a string
Python throws:
pgsqlCopy codeAttributeError: 'list' object has no attribute 'split'
✅ Fix
You need to unwrap the inner list. Since you are processing one testimony at a time, take the first element:
pythonCopy code# process only this testimony
sentences = segment_hebrew_spacy_texts([row['text']], nlp=nlp)[0] # <-- take first (and only) item
Now sentences is a flat list of strings, and sent.split() will work correctly.
Optional: safer version
pythonCopy codesentences_list = segment_hebrew_spacy_texts([row['text']], nlp=nlp)
sentences = sentences_list[0] if sentences_list else []
This avoids errors if the function returns an empty list for some reason.
User
It prints this:
"Using CPU"
Should I make it use the GPU|
Assistant
Yes — if you have a GPU available (and your Slurm script requests --gres=gpu:a10:1), you can and should use it for the transformer model (he_ner_news_trf). Processing on CPU will be much slower, and transformer models are GPU-optimized.
Here’s how to make SpaCy actually use the GPU:
Require GPU
At the start of your script, add:
pythonCopy codeimport spacy
if spacy.prefer_gpu():
print("GPU is available")
spacy.require_gpu() # forces SpaCy to use GPU
else:
print("No GPU available, using CPU")
spacy.prefer_gpu() only checks; it doesn’t automatically use it.
spacy.require_gpu() will make SpaCy load models on GPU.
Optional: Check PyTorch device
he_ner_news_trf is based on transformers. You can also verify:
pythonCopy codeimport torch
print(torch.cuda.is_available()) # should be True
print(torch.cuda.get_device_name(0)) # should show your A10
Notes
If you use GPU, you must have enough GPU memory (transformer models can need several GB).
User
spacy.require_gpu()
File "/cs/labs/oabend/esthersh/edut710/venv3_10/lib/python3.10/site-packages/thinc/util.py", line 212, in require_gpu
raise ValueError("GPU is not accessible. Was the library installed correctly?")
ValueError: GPU is not accessible. Was the library installed correctly?
Assistant
Ah — that error means SpaCy cannot access the GPU, even though your Slurm script requests one. This is not a Python bug; it’s an environment/installation issue. Here’s how to troubleshoot and fix it:
Check that CUDA and PyTorch can see the GPU
Run in Python:
pythonCopy codeimport torch
print(torch.cuda.is_available()) # Should be True
print(torch.cuda.device_count()) # Should be >=1
print(torch.cuda.get_device_name(0)) # Should show your GPU (A10)
If torch.cuda.is_available() is False, SpaCy cannot use GPU either.
Ensure SpaCy has GPU-compatible dependencies
For transformer models, SpaCy relies on Thinc and PyTorch. In your virtual environment, you need:
bashCopy codepip install spacy[cuda]
pip install torch torchvision torchaudio --index-url
Thanks — that explains why SpaCy can’t see the GPU. Your current environment has SpaCy and spacy-transformers, but it lacks a GPU-enabled PyTorch installation. SpaCy itself doesn’t provide GPU support; it relies on PyTorch with CUDA for transformer models.
Here’s what’s missing:
PyTorch with CUDA
You need a version of PyTorch compiled for your cluster’s CUDA version. For example, for CUDA 12.1:
bashCopy codepip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
Replace cu121 with the correct CUDA version on your cluster.
After installing, check in Python:
pythonCopy codeimport torch
print(torch.cuda.is_available()) # Should be True
print(torch.cuda.get_device_name(0)) # Should show your GPU (A10)
User
Assistant
Thanks — I can see the issue clearly now. You have PyTorch installed, but it’s the CPU-only version. That’s why SpaCy cannot use the GPU, even though your system has CUDA libraries (nvidia-cuda-runtime-cu12, etc.) installed.
Notice:
textCopy codetorch 2.1.2
But no CUDA version is specified, and torch.cuda.is_available() would return False. SpaCy relies on GPU-enabled PyTorch.
✅ What’s missing
You need a CUDA-enabled PyTorch version that matches your cluster’s CUDA runtime (looks like CUDA 12.x from your nvidia-cuda-runtime-cu12).
Install PyTorch with CUDA 12.x
Activate your virtual environment and run:
bashCopy codepip uninstall torch torchvision torchaudio -y
Perfect — that means your PyTorch installation can see the GPU. The reason SpaCy still prints "Using CPU" is that you haven’t actually told SpaCy to use the GPU.
Here’s what you should do:
Force SpaCy to use the GPU
pythonCopy codeimport spacy
import torch
if torch.cuda.is_available():
spacy.require_gpu() # this forces SpaCy to use GPU
print("SpaCy is now using the GPU")
else:
print("GPU not available, using CPU")
Place this before loading the model (nlp = spacy.load(...)).
spacy.require_gpu() must be called once before any model is loaded.
Load your transformer model as usual
pythonCopy codenlp = spacy.load("he_ner_news_trf", disable=["tagger", "parser", "ner"])
Now the transformer model will run on GPU. You can check memory usage with:
pythonCopy codeimport torch
print(torch.cuda.memory_allocated())
print(torch.cuda.memory_reserved())
Optional: smaller batches for large texts
pythonCopy codefor doc in nlp.pipe(texts, batch_size=2): # batch_size controls GPU memory
...
Smaller batch → less GPU memory, safer for large testimonies.
User
I there an argument like n_workers that I should use?
Assistant
Yes — SpaCy has a n_process argument in nlp.pipe that controls how many worker processes (CPU cores) are used for parallel processing. This is different from GPU usage.
When to use n_process
If you are on CPU, n_process>1 will parallelize across multiple cores.
On GPU, SpaCy currently uses a single GPU per model, so n_process>1 will not split GPU work across multiple processes; it’s mainly for CPU-heavy pipelines.
Example for CPU:
pythonCopy codefor doc in nlp.pipe(texts, batch_size=100, n_process=4):
sentences = [sent.text for sent in doc.sents]
batch_size: number of texts per batch per worker
n_process: number of CPU processes (cores) to use
GPU and batching
When using GPU:
n_process should usually be 1, because PyTorch will already use the GPU efficiently.
Instead, reduce batch_size to avoid GPU OOM:
pythonCopy codefor doc in nlp.pipe(texts, batch_size=2): # smaller batch for GPU
sentences = [sent.text for sent in doc.sents]
User
I'm still getting this:
spacy.require_gpu() # this forces SpaCy to use GPU
File "/cs/labs/oabend/esthersh/edut710/venv3_10/lib/python3.10/site-packages/thinc/util.py", line 212, in require_gpu
raise ValueError("GPU is not accessible. Was the library installed correctly?")
ValueError: GPU is not accessible. Was the library installed correctly?
Assistant
Ah — now it’s clear. Even though torch.cuda.is_available() returns True, SpaCy still cannot access the GPU. This usually happens when SpaCy’s Thinc backend isn’t compiled with CUDA support, or there’s a mismatch between PyTorch CUDA version and SpaCy/Thinc.
Here’s the breakdown and solution:
Why this happens
Your environment has:
torch 2.1.2 → CUDA-enabled, GPU visible
spacy 3.2.2 + thinc 8.0.17
SpaCy 3.2.2 / Thinc 8.x is old and may not properly detect CUDA on newer PyTorch.
User
Forget the GPU. There's a bug in HebSpacy
Assistant
Ah! Got it — we’re leaving GPU aside. The problem is now with HebSpacy / he_ner_news_trf, not PyTorch or SpaCy’s GPU.
From your earlier error:
pgsqlCopy codeAttributeError: 'list' object has no attribute 'split'
and the way you’re calling:
pythonCopy codesentences = segment_hebrew_spacy_texts([row['text']], nlp=nlp)
we know the issue is HebSpacy returning a nested list.
def basic_stats(df: pd.DataFrame):
"""
Print basic stats about the dataframe.
1. Number of testimonies
2. Average word count per testimony
3. Histogram of word count
:return:
"""
# number of testimonies
print(f"Number of testimonies: {len(df)}")
# average word count per testimony
df["word_count"] = df.text.apply(lambda x: len(str(x).split()))
print(f"Average word count per testimony: {df.word_count.mean()}")
# histogram of word count
plt.hist(df.word_count, bins=50)
plt.xlabel("Word count")
plt.ylabel("Number of testimonies")
plt.title("Histogram of word count per testimony")
plt.show()
if name == 'main':
data = pd.read_csv("../../data/ivritai_transcripts/ivritai_transcripts_with_metadata.csv", index_col=0)
# only keep specific columns
cols = ["text", "Identifier", "Witness Identifier", "עד/ה", "שיוך לקהילה",
"איפה היית ב7/10", "Name", "שפת העדות"]
data = data[cols]
data.rename(columns={"עד/ה": "witness",
"שיוך לקהילה": "community",
"איפה היית ב7/10": "location",
"Name": "name",
"שפת העדות": "testimony_language"}, inplace=True)
# basic_stats(data)
segmented_df = preprocess_text_segments(data, max_words=600)
segmented_df.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
The error you’re seeing is a classic out-of-memory (OOM) issue. Slurm reports:
cppCopy codeDetected 1 oom-kill event(s) in StepId=27790692.batch
…and the process was killed. Even though you requested --mem=64gb, loading and processing your dataset with the he_ner_news_trf SpaCy transformer model can easily exceed that, especially if you keep all intermediate data in memory. Here’s a detailed plan to fix it:
Avoid storing everything in memory
Right now, you keep appending to all_segments inside the loop over every testimony, and then convert it to a DataFrame every iteration. This grows very large very quickly.
Fix: write each processed testimony directly to a CSV, instead of accumulating all in a giant list.
pythonCopy code# before loop
out_path = "../../data/ivritai_transcripts/segmented_sentences.csv"
with open(out_path, "w", encoding="utf-8") as f:
write header
header_written = False
for idx, row in df.iterrows():
...
# build segments list for this testimony
testimony_segments = []
for sent in sentences:
...
testimony_segments.append({
**row.to_dict(),
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
})
# write to CSV incrementally
seg_df = pd.DataFrame(testimony_segments)
if not header_written:
seg_df.to_csv(out_path, index=False, mode='w', encoding="utf-8")
header_written = True
else:
seg_df.to_csv(out_path, index=False, mode='a', header=False, encoding="utf-8")
del testimony_segments, seg_df
gc.collect()
This avoids keeping all segments in RAM at once.
Use SpaCy efficiently
You’re loading the transformer model (he_ner_news_trf) which is huge (~1GB+) and GPU memory hungry. Also, you are not disabling unnecessary components fully and might still load the ner model unnecessarily.
If you only need sentence segmentation, you do NOT need he_ner_news_trf. Use the lightweight he_core_news_sm or he_core_news_md model. Example:
pythonCopy codenlp = spacy.load("he_core_news_sm") # much lighter
If you must use he_ner_news_trf, consider batch processing:
pythonCopy codefor doc in nlp.pipe(texts, batch_size=16):
sentences = [sent.text for sent in doc.sents]
nlp.pipe uses less memory and is faster.
Reduce GPU memory usage
If you still want the transformer model on GPU:
pythonCopy codespacy.require_gpu()
Also, you can try setting environment variable before calling Slurm:
bashCopy codeexport TRANSFORMERS_CACHE=/path/to/big/local/cache
export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128
This helps PyTorch avoid fragmentation issues.
Other memory-saving tips
Delete intermediate variables immediately: del segment, sentences after each iteration.
Call gc.collect() often.
Avoid creating large DataFrames repeatedly inside loops.
Consider chunking the CSV input
If your input CSV is very large (hundreds of MBs or more), load it in chunks:
pythonCopy codefor chunk in pd.read_csv("ivritai_transcripts_with_metadata.csv", chunksize=500):
segmented_chunk = preprocess_text_segments(chunk, max_words=600)
write segmented_chunk to CSV (append mode)
✅ Summary of main change: write segments incrementally to disk instead of storing everything in all_segments. This usually solves OOM errors for transformer-based SpaCy pipelines.
If you want, I can rewrite your preprocess_text_segments function so it doesn’t blow up memory at all and still outputs the same CSV. This would likely eliminate the OOM completely.
Do you want me to do that?
# split into word chunks
for i in range(0, len(words), chunk_size):
chunk = " ".join(words[i:i+chunk_size])
doc = nlp(chunk)
sentences.extend([sent.text for sent in doc.sents])
return sentences
chunk_size is adjustable (e.g., 500–2000 words depending on GPU memory).
This prevents nlp() from trying to process very long texts all at once.
Option 2: Use nlp.pipe for multiple texts
If you already have many testimonies in a list:
pythonCopy codedef segment_hebrew_spacy_texts(texts, nlp, batch_size=8):
"""
texts: list of testimony texts
Returns list of list of sentences
"""
all_sentences = []
for doc in nlp.pipe(texts, batch_size=batch_size):
all_sentences.append([sent.text for sent in doc.sents])
return all_sentences
This is faster and more memory-efficient than calling nlp(text) one by one.
batch_size controls GPU memory usage.
💡 Tip: If you only need sentence segmentation (no NER or transformers), you can also switch to he_core_news_sm. It’s much lighter, uses less RAM/GPU, and works well for segmentation.
If you want, I can rewrite your full preprocess_text_segments function using the chunked approach so it won’t crash on large testimonies and writes CSV incrementally. This would likely fix the OOM completely.
Do you want me to do that?
Help me solve this new error:
"""
import random
import time
import pandas as pd
import matplotlib.pyplot as plt
import spacy
import gc
def segment_hebrew_spacy(text, nlp):
doc = nlp(text)
return [sent.text for sent in doc.sents]
def segment_hebrew_spacy_texts(texts, nlp, batch_size=8):
"""
texts: list of testimony texts
Returns list of list of sentences
"""
all_sentences = []
for doc in nlp.pipe(texts, batch_size=batch_size):
all_sentences.append([sent.text for sent in doc.sents])
return all_sentences
def preprocess_text_segments(df: pd.DataFrame, max_words: int) -> pd.DataFrame:
"""
Divide the text into segments of approx max_words words each.
Make sure to not split sentences.
Add a column "segment_id" to the dataframe to identify each segment.
The ids should be in the format <testimony_id>_<segment_number>.
1. If a testimony has less than max_words, it should have a single segment with segment_number 0.
2. If a testimony has more than max_words, it should be split into multiple segments, each with segment_number starting from 0.
"""
all_segments = []
# Get sentences
print("Loading SpaCy model...")
if spacy.prefer_gpu():
print("Using GPU")
else:
print("Using CPU")
# spacy.require_gpu()
start = time.time()
nlp = spacy.load("he_ner_news_trf", disable=["tagger", "parser", "ner"]) # Requires GPU for best performance
print(f"Model loaded in {(time.time() - start):.2f} seconds\n")
print("Segmenting sentences...")
print()
for idx, row in df.iterrows():
identifier = row['Identifier']
testimony_id = identifier.split(".")[-1] if pd.notna(identifier) else str(random.randint(100000, 999999))
# process only this testimony
# sentences = segment_hebrew_spacy(row['text'], nlp=nlp)
sentences = segment_hebrew_spacy_texts([row['text']], nlp=nlp)
segment = ""
segment_word_count = 0
segment_number = 0
for sent in sentences:
sent_word_count = len(sent.split())
if segment_word_count + sent_word_count > max_words:
all_segments.append({
**row.to_dict(), # keep metadata
# 'testimony_id': testimony_id,
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
})
segment_number += 1
segment = sent
segment_word_count = sent_word_count
else:
segment = f"{segment} {sent}".strip()
segment_word_count += sent_word_count
if segment:
all_segments.append({
**row.to_dict(), # keep metadata
# 'testimony_id': testimony_id,
'tid_order': f"{int(testimony_id)}_{segment_number}",
'text': segment.strip(),
'word_count': segment_word_count
})
# save progressively
res = pd.DataFrame(all_segments)
res.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
print(f"Processed testimony {identifier} into {segment_number + 1} segments.")
# clear memory
del res
gc.collect()
minutes = int((time.time() - start) / 60)
print(f"Segmentation done in {minutes} minutes")
res = pd.DataFrame(all_segments)
# set index to tid_order
res.set_index('tid_order', inplace=True)
return res
def basic_stats(df: pd.DataFrame):
"""
Print basic stats about the dataframe.
1. Number of testimonies
2. Average word count per testimony
3. Histogram of word count
:return:
"""
# number of testimonies
print(f"Number of testimonies: {len(df)}")
# average word count per testimony
df["word_count"] = df.text.apply(lambda x: len(str(x).split()))
print(f"Average word count per testimony: {df.word_count.mean()}")
# histogram of word count
plt.hist(df.word_count, bins=50)
plt.xlabel("Word count")
plt.ylabel("Number of testimonies")
plt.title("Histogram of word count per testimony")
plt.show()
if name == 'main':
data = pd.read_csv("../../data/ivritai_transcripts/ivritai_transcripts_with_metadata.csv", index_col=0)
# only keep specific columns
cols = ["text", "Identifier", "Witness Identifier", "עד/ה", "שיוך לקהילה",
"איפה היית ב7/10", "Name", "שפת העדות"]
data = data[cols]
data.rename(columns={"עד/ה": "witness",
"שיוך לקהילה": "community",
"איפה היית ב7/10": "location",
"Name": "name",
"שפת העדות": "testimony_language"}, inplace=True)
# basic_stats(data)
segmented_df = preprocess_text_segments(data.head(2), max_words=600)
segmented_df.to_csv("../../data/ivritai_transcripts/segmented_sentences.csv")
"""
Traceback (most recent call last):
File "/cs/labs/oabend/esthersh/edut710/holocaust_references/running_on_ivritai_trans/preprocess.py", line 146, in
segmented_df = preprocess_text_segments(data.head(2), max_words=600)
File "/cs/labs/oabend/esthersh/edut710/holocaust_references/running_on_ivritai_trans/preprocess.py", line 69, in preprocess_text_segments
sent_word_count = len(sent.split())
AttributeError: 'list' object has no attribute 'split'
Do you want me to also update your preprocessing loop to be fully memory-efficient with this fix? That would prevent OOMs and incremental CSV writing.
If OOM occurs on GPU, reduce batch sizes in nlp.pipe():
pythonCopy codefor doc in nlp.pipe(texts, batch_size=2): # smaller batch
...
Keep in mind: smaller batch → less memory, slightly slower.
If you want, I can rewrite your preprocess_text_segments to:
Force GPU usage,
Use nlp.pipe efficiently,
Write CSV incrementally,
Avoid OOM completely.
This would make it safe for both CPU and GPU.
Do you want me to do that?
Replace cu121 with the CUDA version installed on your cluster (e.g., 11.8 or 12.1).
Then check again with torch.cuda.is_available().
Check Slurm environment
Sometimes Slurm allocates the GPU, but the environment variable isn’t set. Make sure your job script exports CUDA_VISIBLE_DEVICES:
bashCopy code#SBATCH --gres=gpu:a10:1
inside the script:
echo "CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
If it prints nothing, SpaCy/PyTorch won’t see the GPU.
You can set it manually as a test:
bashCopy codeexport CUDA_VISIBLE_DEVICES=0
Quick CPU fallback
If GPU access isn’t possible on your cluster, you can safely run on CPU:
pythonCopy codenlp = spacy.load("he_ner_news_trf", disable=["tagger", "parser", "ner"])
CPU is slower but works
Consider using he_core_news_sm if only sentence segmentation is needed — it’s lightweight and fast on CPU.
I can give you a fully safe version of your preprocessing script that:
Automatically uses GPU if available,
Falls back to CPU if not,
Avoids OOM by chunking and incremental CSV writing.
This way, it will run on any environment without crashing.
Do you want me to do that?
Optional: Upgrade SpaCy (recommended)
Your SpaCy version is 3.2.2. The latest 3.x versions have better GPU handling with transformers. You could upgrade:
bashCopy codepip install -U spacy
pip install -U spacy-transformers
Verify SpaCy can see GPU
pythonCopy codeimport spacy
import torch
print("Torch CUDA available:", torch.cuda.is_available())
if torch.cuda.is_available():
spacy.require_gpu()
If this works without errors, your he_ner_news_trf model will run on GPU.
✅ Summary: The key missing piece is PyTorch with CUDA. SpaCy-transformers alone doesn’t enable GPU. Once PyTorch is installed correctly, your previous spacy.require_gpu() call should work.
If you want, I can give you a full Slurm-compatible installation sequence that ensures SpaCy + Transformers + GPU will run safely. This will let your preprocessing script run on GPU without errors.
Do you want me to do that?
pythonCopy codeimport torch
print(torch.cuda.is_available()) # Should be True
print(torch.cuda.get_device_name(0)) # Should show A10
Test SpaCy GPU
pythonCopy codeimport spacy
import torch
if torch.cuda.is_available():
spacy.require_gpu()
print("SpaCy using GPU!")
else:
print("GPU not available, using CPU")
Optional
Keep spacy-transformers and he-ner-news-trf as-is.
You do not need to change anything else in your preprocessing code — once PyTorch is GPU-enabled, spacy.require_gpu() will work.
If you want, I can give you a step-by-step Slurm-friendly setup for GPU PyTorch + SpaCy so you can run your preprocess.py safely on GPU. This will fix both the “Using CPU” issue and reduce runtime drastically.
Do you want me to do that?
If you want, I can rewrite your preprocess_text_segments function to:
Use GPU if available,
Fall back to CPU safely,
Write CSV incrementally to avoid OOM,
Work efficiently with long texts.
This will make your preprocessing fully robust.
Do you want me to do that?
If your GPU has plenty of memory, you can increase batch_size for speed.
✅ Recommendation
CPU: use n_process to speed up processing on multiple cores.
GPU: use batch_size to control memory; keep n_process=1.
I can rewrite your preprocess_text_segments loop to automatically:
Use GPU if available,
Adjust batch_size for GPU safely,
Fall back to CPU with n_process for parallelism,
Write CSV incrementally to avoid memory issues.
This will make it fully robust.
Do you want me to do that?
spacy.require_gpu() relies on Thinc’s CUDA support, not just PyTorch.
So SpaCy/Thinc thinks GPU is not accessible, even though PyTorch sees it.
SpaCy 3.6+ and Thinc 8.3+ have robust GPU detection with recent PyTorch.
After upgrading, spacy.require_gpu() should work.
Option B — Use CPU
If upgrading is difficult, you can skip spacy.require_gpu():
pythonCopy code# CPU-only
nlp = spacy.load("he_ner-news-trf", disable=["tagger", "parser", "ner"])
Slower, but works reliably.
For sentence segmentation only, you could use he_core_news_sm (small CPU model) — much faster than transformers on CPU.
Optional — check Thinc GPU availability manually
pythonCopy codefrom thinc.api import require_gpu
print(require_gpu()) # Returns True if Thinc can see a GPU
If this fails, it confirms that your current Thinc/SpaCy version cannot access GPU.
✅ Summary:
Your current SpaCy version is too old for proper GPU support with your PyTorch.
Solution: upgrade SpaCy + Thinc + spacy-transformers OR use CPU models.
I can write a fully working preprocessing script that:
Automatically detects GPU (new SpaCy),
Falls back to CPU if GPU isn’t usable,
Handles large texts efficiently,
Writes CSV incrementally to avoid OOM.
This would let you run your pipeline safely regardless of GPU availability.
Do you want me to do that?
Key points about HebSpacy (he_ner_news_trf):
When you call nlp.pipe([text]) or nlp(text), HebSpacy sometimes returns doc.sents as a generator/list in a nested way.
So if you wrap it in your segment_hebrew_spacy_texts, you get [[sent1, sent2, ...]].
Then your preprocessing loop does:
pythonCopy codefor sent in sentences:
sent_word_count = len(sent.split())
Here sent is actually a list, hence the AttributeError.
How to fix this
Unwrap the nested list:
pythonCopy codesentences_list = segment_hebrew_spacy_texts([row['text']], nlp=nlp)
sentences = sentences_list[0] if sentences_list else []
This guarantees sentences is a flat list of strings.
Safer version of segment_hebrew_spacy_texts
pythonCopy codedef segment_hebrew_spacy_texts(texts, nlp, batch_size=1):
"""
Returns a list of sentence lists, one per text.
Ensures no nested lists.
"""
all_sentences = []
for doc in nlp.pipe(texts, batch_size=batch_size):
# convert doc.sents to list of strings
sents = [str(sent) for sent in doc.sents] # force strings
all_sentences.append(sents)
return all_sentences
Using batch_size=1 avoids HebSpacy weirdness with long texts.
Always cast sent to str to avoid generators causing a list-of-lists.
Update your loop:
pythonCopy code# process only this testimony
sentences = segment_hebrew_spacy_texts([row['text']], nlp=nlp)[0] # unwrap
for sent in sentences:
sent_word_count = len(sent.split())
...
This fixes the AttributeError and works with HebSpacy quirks.
If you want, I can rewrite your full preprocess_text_segments function to:
Avoid HebSpacy list-of-lists issues,
Handle large texts safely,
Incrementally write CSV to prevent memory issues,
so you won’t run into errors even with very long testimonies.
Do you want me to do that?