r/MLQuestions • u/curiousman7366 • 2h ago
r/MLQuestions • u/SignificantZebra5883 • 3h ago
Natural Language Processing π¬ help me get to 98 % on this coreference dataset? custom head on mmBERT, stuck at 90 %
hey guys, im trying to make a custom head that groups the words in a text that refer to the same entity (coreference). every mention picks ONE earlier mention, or "none" if it is a new thing.
ive been trying for a day and cant get past about 90 % right picks. could you please look at the architecture?
this is the whole thing: load the dataset, add the head, train on everything twice, test.
# Czech coreference as a CHOICE: every mention picks ONE earlier mention, or "none" (= a new thing).
# mmBERT-base (all of it trains) + a tiny head, 2 passes over the training data. pip install torch transformers datasets
import random, torch, torch.nn as nn, torch.nn.functional as F
from datasets import load_dataset
from transformers import AutoModel, AutoTokenizer
dev = "cuda" if torch.cuda.is_available() else "mps"
random.seed(0); torch.manual_seed(0)
tok = AutoTokenizer.from_pretrained("jhu-clsp/mmBERT-base")
bert = AutoModel.from_pretrained("jhu-clsp/mmBERT-base").to(dev)
head = nn.Sequential(nn.Linear(3 * 768, 256), nn.ReLU(), nn.Linear(256, 1)).to(dev)
data = load_dataset("lattice-nlp/corefud-1-4").filter(lambda lang: lang == "cs", input_columns="language") # CorefUD 1.4, the Czech part
def prep(doc):
"""-> tokens, the token of every mention's head word (in text order), the entity id of every mention"""
enc = tok(doc["text"], return_offsets_mapping=True, return_tensors="pt")
off = enc.pop("offset_mapping")[0].tolist(); end = max(e for s, e in off)
m = sorted((m["head_onset"], max(i for i, (s, e) in enumerate(off) if e > s and s < m["head_offset"]), m["COREF"])
for m in doc["mentions"] if m["type"] == "entity" and m["head_offset"] <= end)
return enc.to(dev), torch.tensor([t for _, t, _ in m], device=dev), torch.tensor([g for _, _, g in m], device=dev)
def scores(enc, t):
"""-> table (n, n + 1). one row per mention. column 0 = "none", column j + 1 = "the same thing as mention j" """
v = bert(**enc).last_hidden_state[0][t]; n = len(t) # one vector per mention
A, B = v[:, None].expand(n, n, -1), v[None].expand(n, n, -1)
pair = head(torch.cat([A, B, A * B], dim=2)).squeeze(2) # the score of "mention i is the same thing as mention j"
pair = pair.masked_fill(~torch.ones(n, n, dtype=torch.bool, device=dev).tril(-1), float("-inf")) # only EARLIER mentions can be picked
return torch.cat([torch.zeros(n, 1, device=dev), pair], dim=1) # "none" always has the score 0
def right(g):
"""True where an option is a right answer: every earlier mention of the same entity, or "none" when there is no such mention"""
same = (g[:, None] == g[None, :]).tril(-1)
return torch.cat([~same.any(dim=1, keepdim=True), same], dim=1)
def test():
"""the dev documents, which the model never trains on -> share of mentions whose top pick is right"""
bert.eval(); hit = total = 0
with torch.no_grad():
for doc in data["dev"]:
enc, t, g = prep(doc)
if len(t) > 1:
hit += right(g)[torch.arange(len(t)), scores(enc, t).argmax(dim=1)].sum().item(); total += len(t)
bert.train()
return f"right picks on {total:,} unseen mentions: {hit / total:.2%}"
EPOCHS, N = 2, len(data["train"]) # 1 step = 1 document. 5,679 documents, seen twice
opt = torch.optim.AdamW([{"params": head.parameters(), "lr": 1e-4}, {"params": bert.parameters(), "lr": 2e-5}], fused=True)
sched = torch.optim.lr_scheduler.LinearLR(opt, 1.0, 0.0, EPOCHS * N) # both learning rates fall in a straight line to 0
bert.train()
for step, i in enumerate([i for _ in range(EPOCHS) for i in random.sample(range(N), N)], 1):
enc, t, g = prep(data["train"][i])
if len(t) > 1:
logp = F.log_softmax(scores(enc, t), dim=1)
loss = -torch.logsumexp(logp.masked_fill(~right(g), float("-inf")), dim=1).mean() # minus log of the probability that sits on the right options
opt.zero_grad(); loss.backward(); opt.step()
sched.step()
if step % 100 == 0:
print(f"step {step} of {EPOCHS * N} | loss {loss.item():.3f}", flush=True)
if dev == "mps": torch.mps.empty_cache() # hands unused GPU memory back (Apple only)
if step % N == 0: print(f"epoch {step // N} done | " + test(), flush=True)on my mac mini (M4 pro, 24 GB) it takes about 38 minutes and prints 88.4 % after epoch 1 and 89.7 % after epoch 2.
im vibe coding most of this, so please let me know if i overlooked something critical. what i found so far:
a gentle LR for the head (1e-4, not 1e-3) keeps its neurons alive, but the score stays the same
the head doesnt really matter. wider, deeper, a transformer block inside it: same score
a bigger base barely helps, which is puzzling. XLM-RoBERTa-large with 4 epochs gets 90.75 %, and EuroBERT-610m is far worse (it never saw czech)
a 3rd epoch gives nothing
when both models are wrong, they pick the very same wrong option 80 % of the time
the dataset is public (CorefUD 1.4, the czech part), so this is perfectly reproducible. and the labels look about 98 % right, according to a blind check i ran with opus on the wrong picks.
could you guys help me reach 98 % on this dataset? thanks!
r/MLQuestions • u/Ambitious_Stuff3322 • 1d ago
Career question πΌ Title: How can I crack ML internships as a fresher? Looking for advice! Hey everyone! I'm a final-year B.Tech AIML student preparing for Machine Learning internships. I've learned Python, basic ML algorithms, model evaluation and Scikit-learn. I've also started building practical projects, includ
I'm a final-year B.Tech student specializing in Artificial Intelligence and Machine Learning, and I'm currently preparing for Machine Learning Engineer internship opportunities.
I've been learning ML practically and working on improving my skills. So far, I've covered:
- Python, NumPy, Pandas and Scikit-learn.
- Linear Regression, Logistic Regression and Gradient Descent.
- Model evaluation metrics such as Precision, Recall and F1-score.
- Basic model training, testing and evaluation.
- Building practical ML projects.
I'm also working on projects involving:
- ML Model Monitoring Dashboard (data drift, model drift and performance monitoring).
- Automated ML Retraining Pipeline.
- A Retrieval-Augmented Generation (RAG) system.
However, I want to understand what companies actually expect from ML interns, especially product-based companies and startups.
I'd love advice from people who have successfully secured ML internships or are currently working as ML engineers.
A few questions:
What technical skills should I focus on to become internship-ready?
How important are DSA and SQL for ML internship interviews?
What kind of projects actually make a resume stand out?
Should I focus more on ML fundamentals, Deep Learning, NLP or deployment/MLOps?
How do you find and apply for genuine ML internship opportunities?
What does the actual ML internship interview process look like?
What mistakes should beginners avoid while preparing?
I'm not looking for shortcuts. I genuinely want to become good at this field and build the skills required to contribute to a real engineering team.
If you've been through this journey, please share your experience, resources, preparation strategies or even mistakes you made.
Any honest advice would be incredibly helpful. Thank you!
r/MLQuestions • u/tattoosbyhannah • 20h ago
Beginner question πΆ Are you thinking of attending: UT Austinβs Postgraduate Program in AI and Machine Learning for Business Applications?
reddit.comr/MLQuestions • u/overwhelmed_coconut • 21h ago
Natural Language Processing π¬ How to find signature pages in thousands of contracts with no fixed layout? (can't afford to misclassify a full contract)[D]
reddit.comr/MLQuestions • u/SignificantZebra5883 • 1d ago
Beginner question πΆ Coming from Karpathy's makemore, how to actually experiment with models in practice?
I've finished the karpathy makemore series which i enjoyed a lot and created some of my own neural nets. Now i thought about actually checking the architecture of some of the popular models and try to fine-tune them and watch the loss go down and stuff. (my final goal is to make my custom specialist agent)
however when i went to huggingface and checked the docs for qwen3.5-0.8B all i found was openai implementation or some transformers library. for example:
from openai import OpenAI
# Configured by environment variables
client = OpenAI()
messages = [
{"role": "user", "content": "Give me a short introduction to large language models."},
]
chat_response = client.chat.completions.create(
model="Qwen/Qwen3.5-0.8B",
messages=messages,
max_tokens=32768,
temperature=1.0,
top_p=1.0,
presence_penalty=2.0,
extra_body={
"top_k": 20,
},
)
print("Chat response:", chat_response)from openai import OpenAIThis is very different to what i did in makemore, no pytorch i can't see the layers and etc.
So im coming to you all whom are probably much more experienced in this. are there some special docs im missing? where do i actually get the "raw" code?
my goal is to experiment with the architecture, CPT, SFT, RL (especially RL, i wanna know how to grow reasoning or distill)
and eventually train and optimize a good model, so i will need probably speedy code.
Could you guys give me any pointers? thanks a lot!
r/MLQuestions • u/Plastic_Choice6076 • 2d ago
Other β Understand theory, can't code
So I know a lot about ml and ai engineering , like iam working on a rag project, I know (to a limit though) what chunking strat to use , how the pipeline should look like , etc , but I can't code those stuff , I can vibe code my way to make a full working end to end pipeline
So idk thoughts on that and any suggestions would be appreciated
r/MLQuestions • u/RoofProper328 • 2d ago
Datasets π Where do teams find medical datasets that are actually licensed for commercial use?
I've been looking into medical data for training models (clinical speech/dictation, EHR text, and imaging like CT, MRI and X-ray), and I keep running into the same problem.
Most of the well-known datasets (MIMIC, CheXpert, PhysioNet sets, etc.) are research-only or have credentialing rules that rule out commercial use. That's fine for papers, but it doesn't help if you're building a product.
A few questions for anyone who has been through this:
Where did you end up sourcing commercially usable medical data? Hospital partnerships, data vendors, synthetic data, something else?
How did you check that it was properly de-identified (HIPAA Safe Harbor or similar)?
Roughly what did licensing cost, or how was it priced (per hour of audio, per record, per study)?
Is anyone using synthetic medical data in production, and does it hold up?
r/MLQuestions • u/Mental_Impression699 • 2d ago
Unsupervised learning π Why did a plain MLP beat my topology-predicting JEPA on kinematic tasks β and where should a topological target actually win?
Looking for intuition from people who've thought about self-supervised objectives.
I built a small JEPA variant that, instead of predicting a learned embedding for a masked region, predicts the region's topology β computed exactly (union-find watershed): how many basins form, persistence, volume. Trained on particle-physics data (CMS Open Data).
Results that confused me:
On the native topological task it's strong: basin-count accuracy 0.945 vs 0.572 majority-class baseline.
But on downstream kinematic tasks, a plain MLP on raw kinematics beats it. Jet multiplicity MSE: 0.0103 (mine) vs 0.0016 (MLP). Dimuon mass: 25,211 vs 24,640. I pre-registered three bars and only hit 1.
My two questions:
Why does the MLP win here? My current guess: kinematic quantities (mass, multiplicity) are basically smooth functions of the raw inputs, so a model that throws away pointwise values to keep only topological structure is discarding exactly the signal the task needs. Topology is invariant to deformations β but these tasks want the deformation. Is that the right way to think about it, or am I missing something?
Where should a topological prediction target actually win? My intuition says tasks where connectivity/shape is the label β phase-transition detection, segmentation, counting discrete objects, graph-structured data β not smooth regression. Are there known results on when topological features beat raw features in SSL? Pointers very welcome.
https://github.com/teerthsharma/Alcyone-W
https://huggingface.co/teerthsharma/Alcyone-W
Is it because I trained too little or something ? I have 2 Blackwell rtx 6000 on vm can have a h100 training schedule if thatβs the case my prior work or more detail about this project at www.teerth.dev any pointers helps
r/MLQuestions • u/Fresh_Mud8613 • 2d ago
Other β BRT/RF vs. Bayesian Methods
I am trying to do a spatial study predicting occurrence. I have a whole bunch of geographic covariates stored as rasters and want to use a method to compare their associations with an occurrence (it's logistic, it either happened or it didn't). I know how to use BRTs and RF and think they would be an applicable methodology. But other people are using Bayesian methods to help with spatial autocorrelation etc. I have reasons that I'd rather do ML but I need to have my rationale water tight.
Is anyone able to have an opinion or have a discussion about the differences? I could use anything I can get. Chat GPT is just being sycophantic at this point.
r/MLQuestions • u/Creative-Act-7455 • 2d ago
Beginner question πΆ We tried active inference for fault diagnosis under drift
it matched classic methods but never beat them in a pre-registered test. Where is our mistake? In the end we did end up with some very strange results. The complete Tests, Data and a repo with a rust workbench for testing as well as all the results you can find at Repository: https://github.com/dx111ge/inferenceLearning
r/MLQuestions • u/No-Introduction-441 • 3d ago
Beginner question πΆ I want to seriously get into ML/AI engineering and research. How would you approach learning it from scratch today?
Hello everyone hope you are well, I know this is a lot but I'd appreciate the help.
I'm looking to seriously get into machine learning, AI engineering, and eventually research, and I'd appreciate some advice from people who are already working or studying in these fields.
I have a programming background and know the basics of Python. I've studied mathematics before, but I'm rusty and will need to revisit linear algebra, calculus, probability, and statistics.
I'm not looking for shortcuts or a guaranteed job roadmap. I'm trying to figure out how to spend my time effectively, build meaningful projects, and avoid tutorial hell.
I'm willing to dedicate 20+ hours a week to learning, and I'm approaching this as a long-term commitment rather than trying to land an AI job in a few months.
My goal is to actually understand how ML works, from the mathematics and algorithms to training models, experimenting, and eventually reading and implementing research papers.
I also want to build things throughout the learning process, rather than spending months watching tutorials and copying projects without understanding them.
I've started putting together a roadmap that begins with Python, NumPy, and mathematics, then moves into classical ML, deep learning, PyTorch, and eventually ML engineering and research.
But before committing to it, I'd really appreciate some perspectives:
If you were starting ML from scratch today, what would your learning path look like? What would you prioritize, and what would you avoid?
What books, documentation, or other resources helped you actually understand ML? I'm particularly interested in books and hands-on learning rather than relying entirely on video courses.
What projects should a beginner build to develop real understanding? I'm not looking for projects that just look impressive on GitHub. I want projects that force me to understand the algorithms, mathematics, training process, and evaluation.
How do you transition from learning ML to doing research? When should someone start reading papers, reproducing experiments, or investigating their own research questions?
What separates someone who has completed ML courses from someone who is actually ready for an entry-level ML engineering or research engineering opportunity? What skills and evidence of ability do employers or researchers look for?
How important is traditional software/backend engineering knowledge for ML engineering? Should I study it alongside ML, or focus on the ML fundamentals first?
My long-term goal is to become technically competent enough to contribute to real AI/ML projects, collaborate with experienced engineers and researchers, and hopefully work professionally in the field.
I'd especially appreciate hearing from ML engineers, research engineers, researchers, or people who have successfully made this transition.
Thank you all very much!
r/MLQuestions • u/ysjSouth_Pollution_ • 3d ago
Beginner question πΆ B.Pharm student looking for help with a CNN-based project in Pharmacognosy!
reddit.comr/MLQuestions • u/Mysterious_Guava3663 • 3d ago
Beginner question πΆ i started ml last week as an intermediate web developer! not sure if im even improving?
reddit.comr/MLQuestions • u/Inevitable-Doubt2399 • 3d ago
Beginner question πΆ Ai Ml Dl resources
reddit.comr/MLQuestions • u/Clause_8 • 4d ago
Beginner question πΆ Are there effective frameworks for using AI?
I use generative AI almost every day, and have found that it improves the quality of my work. However, hearing about the Reimann hypothesis proof, I'm wondering if I'm doing things wrong, since the level of improvement I'm seeing definitely isn't on the level of solve century old holy grail of mathematics. Does anyone have any recommendations as to effective frameworks for ways of getting the maximum benefit from generative AI, preferably from peer reviewed research which actually measures the improvement and indicates any tradeoffs (e.g., productivity versus accuracy)?
r/MLQuestions • u/MolocManager • 4d ago
Beginner question πΆ How do you evaluate open weight models (for personal use) vs picking whichever frontier model tops leaderboards?
Some friends and I are hacking on a few things to git gud at AI beyond the models everyone's already using. We're picking open weight models for a few real tasks, but the jobs are all over:
structured extraction from various docs/assets, 2) classification or triage tasks, 3) Q&A querying your own materials like RAG, 4) templatized/structured summaries, 5) coding, 6) work in languages that arenβt English (use non-Roman alphabet). We've just been testing & debating but need some structure to move forward.
Public leaderboards havenβt helped much. Imo scores depend a lot on who runs the test and how, and the tests rarely look like my real work
SELECTION - How are you accessing the most relevant OS/OW models? Started with OpenRouter but some privacy ppl suggested NY Token Exchange or OmniRouter. Haven't set it up yet, unsure of what tradeoffs more private models have, like speed.Β
TESTING - Did you build your own test set from real tasks? How many examples did it take before you felt OK trusting the results? Where should I go for pre-built evals?Β
Reading recs are welcome as well, since Iβm kinda new to this.
r/MLQuestions • u/everydayreligion1090 • 4d ago
Other β Looking for 3 comprehensive courses to build strong foundations in AI, ML, and Deep Learning before starting projects
hi everyone
so im a computer science graduate looking to rebuild my foundations in artificial intelligence, machine learning, and deep learning
ive studied some of these subjects before but ive forgotten quite a bit so id like to start again with a structured learning path
my goal is simple
complete three comprehensive and affordable courses, one for each subject, and then start building projects, reading research papers, and conducting literature reviews
ideally im looking for
1 artificial intelligence fundamentals
a course covering the major concepts and branches of ai including classical ai, search algorithms, knowledge representation, reasoning, planning, and an introduction to modern ai
2 machine learning fundamentals
a course covering the major ml approaches including supervised learning, unsupervised learning, reinforcement learning, regression, classification, clustering, decision trees, ensemble methods, model evaluation, and other essential concepts
3 deep learning fundamentals
a course covering neural networks, backpropagation, optimization, cnns, rnns, lstms, attention, transformers, generative models, and other major deep learning architectures
my preferences
coursera, edx, university courses, or any reputable platform
courses must be affordable and preferably free or reasonably priced
preferably taught by respected university professors or established ai researchers
beginner friendly explanations but with enough technical depth to understand research papers
a balance of theory, mathematics, and practical programming
preferably one comprehensive course per subject but im open to specializations if a single course isnt sufficient
im not trying to become an expert in every ai subfield before starting projects
i just want a solid broad foundation so i can understand the terminology, read academic literature, conduct literature reviews, and independently learn more advanced subjects when needed
for those who have taken these courses which three would you recommend and why
id particularly appreciate recommendations based on firsthand experience including any important topics the courses leave out
thanks
r/MLQuestions • u/CerealConMiel • 4d ago
Beginner question πΆ Does computing Group_size on train+test (no target) cause leakage? Reviewing a method from a Medium article
Hi everyone,
I'm working on the Spaceship Titanic competition and I'd like to get your opinion on a feature engineering decision that appears in a popular Medium article. I want to check whether the method is sound or if it introduces data leakage.
Reference article:
The issue: Kaggle splits passengers randomly between train and test, so some groups are split across both sets. If `Group_size` (number of passengers in the same group, extracted from `PassengerId`, e.g. `0001_01`, `0001_02` belong to group `0001`) is computed separately in train and test:
# In train
train['Group_size'] = train['Group'].map(train['Group'].value_counts())
# In test
test['Group_size'] = test['Group'].map(test['Group'].value_counts())
...the same group can get different sizes in train and test. Example: group `0001` has 3 members total (2 in train, 1 in test) β train says `Group_size = 2`, test says `Group_size = 1`. Inconsistent, and neither reflects the true size.
The alternative (which I believe the article uses, or something similar) is to compute group sizes using train + test together, without touching the target:
all_df = pd.concat([train, test], ignore_index=True)
all_df['Group_size'] = all_df.groupby('Group')['PassengerId'].transform('count')
train = all_df.iloc[:len(train)].copy()
test = all_df.iloc[len(train):].copy()
This makes `Group_size` consistent and reflects the real group size.
My questions:
Is computing `Group_size` on train+test (excluding `Transported`) considered data leakage? My reasoning is no: it only uses `PassengerId`/`Group` (identifiers), never the target. The group size is a real-world fact, not a label being peeked at.
Is this transductive feature engineering generally accepted in Kaggle competitions, or discouraged even when the target isn't involved?
Does the same consistency issue apply to other derived features (`Deck`, `Side`, `CabinNum`, `FamilySize` from `Cabin`/`Name`)? Should those also be computed globally (train+test) to avoid train/test mismatch?
Has anyone reviewed the preprocessing method in the article above? I'd appreciate feedback on whether it's a solid approach or if there are pitfalls (especially around the train/test split consistency).
I'd love to hear how experienced Kagglers handle this. Thanks in advance!
r/MLQuestions • u/No-Act-8939 • 5d ago
Beginner question πΆ Where to get started?
reddit.comr/MLQuestions • u/jgcoelho_real • 5d ago
Beginner question πΆ How do I stop Gemma 26B E4B from behaving like this?
It gets the task right and then does not stop thinking ever. It goes something like this:
Writing result... DONE! (Stop). End of thought cycle. Everything is correct. Proceeding to outputting response for the user. All instructions followed. Finalizing. Ready. Outputting now. (End). Thinking block complete. Final answer ready. DONE! (Stop). Actually finished everything in my head. Ready to provide the solution. Done! Go! Finished. Actual final end of thinking process. Writing... DONE! (Stop). End of thought cycle. Everything is correct. Proceeding to outputting response for the user. All instructions followed. Finalizing. Ready. Outputting now. (End). Thinking block complete. Final answer ready. DONE! (Stop). Actually finished everything in my head. Ready to provide the solution. Done! Go! Finished. Actual final end of thinking process. Writing... DONE! (Stop). End of thought cycle. Everything is correct. Proceeding to outputting response for the user. All instructions followed. Finalizing. Ready. Outputting now. (End). Thinking block complete. Final answer ready. DONE! (Stop). Actually finished everything in my head. Ready to provide the solution. Done! Go! Finished. Actual final end of thinking process. Writing... DONE! (Stop). End of thought cycle. Everything is correct. Proceeding to outputting response for the user. All instructions followed. Finalizing. Ready. Outputting now. (End). Thinking block complete. Final answer ready. DONE! (Stop). Actually finished everything in my head. Ready to provide the solution. Done! Go! Finished. Actual final end of thinking process. Writing... DONE! (Stop). End of thought cycle. Everything is correct. Proceeding to outputting response for the user. All instructions followed. Finalizing. Ready. Outputting now. (End). Thinking block complete. Final answer ready. DONE! (Stop). Actually [...]
I already tried including a line in system instructions to respond immediately after finding the answer, but it fails to steer it. It is a bummer that the model gets stuck like this, because it is actually better at writting than Qwen 35B A3B.
r/MLQuestions • u/Familiar9709 • 6d ago
Beginner question πΆ What is the purpose of cross validation, validation and test set?
What is the purpose of these different steps in building a machine learning model? Let's say you have X data points, how should you do the division into the different sets? Should it be 60/20/20? 60% to use for cross validation, 20% for test set and 20% for validation?
If so, what is the purpose of the test set if you already are doing the cross validation step where you take all that data, you make the folds and you test the models?
Unfortunately the information I could gather is quite contradicting and also doesn't consider sometimes the cross validation step, so would be very good if people could explain this in greater detail.
Thanks
r/MLQuestions • u/Cupcake_Timely • 6d ago
Beginner question πΆ The 3 dimensions of an AI system
r/MLQuestions • u/kamesh_singh • 7d ago
Beginner question πΆ Need advice on accurate golf ball tracking using computer vision
I'm trying to build a golf ball tracking app similar to Shot Tracer and SmoothSwing. I've experimented with several open-source AI models, but I haven't been able to achieve reliable tracking accuracy.
The ball is tiny and moves very fast, making it difficult to track consistently across video frames.
I'm looking for advice from people experienced in computer vision, object tracking or ML:
What approaches/models work best for tracking tiny, fast-moving objects?
Should I combine object detection with temporal tracking, optical flow or Kalman filters?
Are there any specific models, datasets or research papers worth exploring?
I'm not looking for a basic YOLO implementation. I'd like to understand how to build a genuinely reliable tracking pipeline.
Any suggestions or experiences would be appreciated!