6.5.11Research Frontiers & Practice

Contributing to open-source ML

4,084 words19 min readdifficulty · medium

What Is Open-Source ML Contribution?

Why this matters: ML research moves fast, but production tools lag behind. Open-source bridges this gap. When you contribute, you:

  1. Force yourself to understand code deeply (can't fake it when submitting a PR)
  2. Learn real-world engineering (testing, API design, backwards compatibility)
  3. Build reputation (your commits are your resume)
  4. Give back (you've used TensorFlow/PyTorch/Scikit-learn—now help the next person)

How to Start Contributing

1. Understanding the Contribution Lifecycle

The journey from idea to merged code:

Find Issue → Claim It → Fork Repo → Create Branch → 
Code + Tests → Submit PR → Code Review → Revisions → Merge

Why each step exists:

  • Find Issue: Prevents duplicate work, ensures maintainers want the change
  • Fork Repo: You need your own copy to experiment without breaking main project
  • Create Branch: Isolates your change, lets you work on multiple features
  • Code + Tests: Tests prove your change works and won't break in the future
  • Code Review: Experts catch mistakes, teach you best practices
  • Revisions: Learning happens here—iterate based on feedback

2. Choosing the Right Project

80/20 Rule: 80% of learning comes from 20% of projects. Pick based on:

  1. You already use it (PyTorch, Scikit-learn, Pandas)
  2. Active maintainers (PRs get reviewed within days, not months)
  3. Good first issues tagged (shows they welcome newcomers)
  4. Codebase you can comprehend (don't start with TensorFlow's C++ backend)

3. The Anatomy of a Good Pull Request

A PR is not just code—it's a persuasive argument that your change should be merged.

Template for a Strong PR:

## Problem
[Link to issue] Users can't load >16GB datasets because DataLoader loads 
everything into memory at once.
 
## Solution
Implement streaming mode that yields batches from disk using memory-mapped files.
 
## Changes
- Added `StreamingDataset` class wrapping `np.memmap`
- Modified `DataLoader` to detect streaming datasets and skip preloading
- Added `stream=True` parameter to dataset constructors
 
## Testing
- Unit test: 50GB dataset loads with<2GB peak memory (test_streaming.py)
- Benchmark: 1% slower iteration vs. in-memory (acceptable tradeoff)
- Backwards compatible: all existing tests pass
 
## Tradeoffs
- 1% slower due to disk I/O, but enables datasets10x larger than RAM
- Requires random-access file format (won't work with compressed .tar.gz)
 
## Docs
- Added "Working with Large Datasets" section to user guide
- Updated docstrings with `stream` parameter explanation

Why each section?:

  • Problem: Proves the change is necessary (not just "I thought this would be cool")
  • Solution: One-sentence summary (reviewer knows what to expect)
  • Changes: Technical detail (what files did you touch?)
  • Testing: Proof it works (maintainers can't merge untested code)
  • Tradeoffs: Shows you thought critically (every design has downsides)
  • Docs: Users need to know the feature exists

4. Code Review Etiquette

Code review is where learning happens. Maintainers have seen patterns you haven't.

Recall Feynman's Explanation (Explain to a 12-year-old)

Imagine you're building a LEGO spaceship and you show it to an expert LEGO builder. They say "Cool! But if you use this piece instead of that one, the wings won't fall off when you pick it up."

You have two choices:

  1. Get defensive: "My design is fine! You just don't get my vision!"
  2. Get curious: "Oh! Why does that piece work better? Teach me!"

Code review is choice #2. The expert has built 100 spaceships. They know which pieces break. When they suggest changes, they're giving you years of experience compressed into one comment. Your job is to ask questions until you understand why their way is better, then improve your spaceship.

Sometimes you'll disagree—that's okay! Explain your reasoning. But if three experts all say "wings will fall off", they're probably right. Trust the process.

How to respond to feedback:

Feedback Type Good Response Bad Response
"This could be clearer" "Good catch! What if I rename X to Y and add comment explaining Z?" "It's clear to me."
"This will break edge case X" "You're right! I'll add a test for that. Should I handle it by doing Y?" "That's an unlikely case."
"Use library function F instead" "Didn't know that existed! Does it handle Z differently than my implementation?" "My implementation works fine."
"This is out of scope for this PR" "Agree, I'll split this into a separate PR. Should I open an issue first?" "But it's related!"

Core principle: Assume good intent. Comments aren't attacks—they're collaboration. Maintainers want your PR to succeed (merging it is less work than rejecting it).

5. Types of Contributions (Beyond Code)

Not all contributions require coding ML algorithms.

Value ladder (increasing difficulty):

  1. Documentation (easiest, highest impact per hour)

    • Fix typos, clarify confusing sections
    • Add examples showing how to use features
    • Translate docs to other languages
  2. Issue triage (helps maintainers prioritize)

    • Reproduce bug reports (add "confirmed" label)
    • Ask for clarifications on vague issues
    • Close duplicates
  3. Tests (improves reliability)

    • Add test cases for uncovered code
    • Write regression tests for fixed bugs
  4. Bug fixes (requires understanding codebase)

    • Fix crashes, incorrect outputs
    • Handle edge cases
  5. Features (highest difficulty, most visible)

    • Implement new algorithms
    • Add configuration options
    • Improve performance

80/20 insight: Documentation and tests are undervalued but high-impact. 80% of contributors try to implement flashy features; 20% improve docs. But users hit docs10x more often than they need new features.

Real-World Workflow Example

Let's trace a complete contribution from finding the issue to merged PR.

Scenario: You're using scikit-learn for a project and notice KMeans is slow.

Step 1: Find the Issue (1 hour)

You profile your code:

import cProfile
cProfile.run('model.fit(X)')
 
# Output shows80% time in _euclidean_distances()

Check GitHub issues: Someone already filed #12345 "KMeans slow for large n_features".

Step 2: Understand the Problem (2 hours)

Read the source code:

# sklearn/cluster/_kmeans.py
def _euclidean_distances(X, centers):
    # Current implementation: pure Python loops
    distances = np.zeros((X.shape[0], centers.shape[0]))
    for i in range(X.shape[0]):
        for j in range(centers.shape[0]):
            distances[i, j] = np.sqrt(np.sum((X[i] - centers[j])**2))
    return distances

Issue: Nested Python loops are slow. NumPy has vectorized cdist for this.

Step 3: Implement Fix (3 hours)

from scipy.spatial.distance import cdist
 
def _euclidean_distances(X, centers):
    # Vectorized computation: 100x faster for large arrays
    return cdist(X, centers, metric='euclidean')

Add test:

def test_euclidean_distances_correctness():
    X = np.random.rand(100, 50)
    centers = np.random.rand(10, 50)
    
    # Compare old (slow but trusted) vs. new (fast
    old_result = _euclidean_distances_old(X, centers)
    new_result = _euclidean_distances(X, centers)
    
    np.testing.assert_allclose(old_result, new_result)
 
def test_euclidean_distances_performance():
    X = np.random.rand(1000, 1000)
    centers = np.random.rand(100, 1000)
    
    import time
    start = time.time()
    _euclidean_distances(X, centers)
    elapsed = time.time() - start
    
    # Should complete in <1 second (old version took 45s)
    assert elapsed < 1.0

Step 4: Submit PR (1 hour)

Write the description (from template above), push to your fork, open PR.

Step 5: Code Review (2 days, async)

Reviewer comment: "This adds a scipy dependency. We want scikit-learn to depend only on NumPy. Can you implement this with NumPy's broadcasting instead?"

Your response: "Good point! Let me try NumPy broadcasting. Is this the right approach?"

def _euclidean_distances(X, centers):
    # Broadcasting: X is (n, d), centers is (k, d)
    # X[:, None, :] is (n, 1, d), centers[None, :, :] is (1, k, d)
    # Subtraction broadcasts to (n, k, d)
    diff = X[:, None, :] - centers[None, :, :]
    return np.sqrt((diff**2).sum(axis=2))

Reviewer: "Perfect! One more thing: add a benchmark to the docs showing the speedup."

You: "Added benchmark section. Speedup is 87x for n=1000, d=1000."

Step 6: Merged! (1 week total)

Your contribution is now in scikit-learn==1.5.0. Thousands of users benefit.

What you learned:

  1. How to profile Python code (cProfile)
  2. NumPy broadcasting mechanics
  3. Dependency management tradeoffs
  4. How to write performance tests
  5. How to collaborate asynchronously

Why this matters: This is real ML engineering. Research papers don't teach you this.

Common Pitfalls and How to Avoid Them

Building Your OS Portfolio

Why it matters: Hiring managers look at GitHub profiles. Your commits are proof you can:

  1. Write production-quality code
  2. Collaborate with strangers
  3. Learn new codebases quickly
  4. Take feedback gracefully

Strategic approach (80/20):

  • 20% of your contributions (features in major projects like PyTorch) generate 80% of visibility
  • But you need the other 80% (small fixes) to build credibility that unlocks the 20%

Roadmap:

  1. Months 1-2: 10 documentation fixes across 3-5 projects (build confidence)
  2. Months 3-4: 5 bug fixes (learn codebases deeply)
  3. Months 5-6: 2 small features (demonstrate design skills)
  4. Months 7+: 1 substantial feature per quarter (become recognized contributor)

By month 12, you have 30+ merged PRs across major projects. That's a portfolio that opens doors.

Connections

  • Code Review Best Practices - Applies to both giving and receiving feedback
  • Software Engineering for ML - OS teaches production ML skills
  • Version Control with Git - Foundation for all OS work
  • Testing ML Systems - OS demands rigorous testing
  • ML Research Paper Implementation - Often starts with OSS reimplementation
  • Collaborative Machine Learning - OSS is ultimate collaboration practice
  • Building ML Portfolios - OS contributions are portfolio centerpieces
  • Technical Writing for ML - Documentation work improves your explanations

Flashcards

What are the 7 steps in the OS contribution lifecycle? :: Find Issue → Claim It → Fork Repo → Create Branch → Code + Tests → Submit PR → Code Review → Revisions → Merge

Why must every PR include tests, not just code?
Tests prove correctness, prevent regressions, and give maintainers confidence to merge. Untested code will break in production as the codebase evolves.
What is gradient checkpointing's memory/compute tradeoff?
Reduces memory from O(L·B·H) to O(L/k·B·H) by storing only every k-th layer activation and recomputing intermediate ones during backward pass. Doubles compute but enables larger batches.
What is the "RAMP" mnemonic for choosing OS projects?
Read code comfortably? Active maintainers? Makes your work easier? People tagged good-first-issues? 3+ yes = good fit.
Why is documentation often higher-impact than features?
Users encounter docs 10x more than they need new features. 80% of contributors chase flashy features, so docs are underserved. Small time investment, large user benefit.
What's the "PR Quality Formula" and why is it multiplicative?
Q = C_correct × C_clear × C_tested × C_justified. Multiplicative because zero on any dimension (e.g., untested) makes PR unmergeable. All must be 1 for merge.
Why start with small PRs rather than large features?
Large PRs are hard to review, sit unreviewed for months.87% of first-timers with 500+ line PRs never return. 73% starting with <50 lines become regular contributors.
What should you do when a code review comment seems wrong?
Assume good intent and ask clarifying questions: "Can you explain why this approach is better? I'm concerned about X." Engage in discussion, don't defend. If 3 experts agree, they're probably right.
How does contributing to OSS teach "real ML engineering"?
You learn profiling, debugging production code, API design, backwards compatibility, performance optimization, testing strategies, and async collaboration—skills research papers don't cover.
What's the strategic OS roadmap for the first year?
Months 1-2: 10 doc fixes (confidence). Months 3-4: 5 bugs (codebase knowledge). Months 5-6: 2 small features (design skills). Months 7+: 1 large feature/quarter (recognition). 30+ PRs by month 12.

Concept Map

motivates

forces

teaches

builds

follows

starts with

then

enables

submitted for

revisions lead to

easiest entry to

proves

Open-Source ML Contribution

Collaboration and Reproducibility

Deep Code Understanding

Real-World Engineering

Reputation and Portfolio

Contribution Lifecycle

Find and Claim Issue

Fork and Branch

Code plus Tests

Code Review

Merge

Documentation Fix

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho yaar, is note ka core idea simple hai: machine learning ki duniya mein sabse zyada growth collaboration aur reproducibility se aati hai. Open-source projects jaise PyTorch, TensorFlow, ya Scikit-learn — yeh wahi jagah hai jaha cutting-edge research actual production tools ban jaate hain. Jab tum contribute karte ho, tum sirf knowledge consume nahi kar rahe, balki poore field ki infrastructure build karne mein help kar rahe ho. Aur sabse important baat — jab tum ek PR (pull request) submit karte ho, tum code ko fake nahi kar sakte. Tumhe usse deeply samajhna padta hai, isliye learning-by-doing sabse powerful tarika ban jaata hai.

Ab yeh matter kyun karta hai, khaaskar tumhare jaise regional student ke liye? Simple — open-source contributions tumhara real portfolio ban jaate hain jo kisi bhi degree ya certificate se zyada bolta hai. Duniya bhar ke experts tumhare code ko review karte hain, tumhe best practices sikhate hain (jaise testing, API design, backwards compatibility), aur yeh sab bilkul free mein. Contribution lifecycle bhi samajhna zaroori hai: pehle ek issue dhoondo, use claim karo, repo ko fork karo, apni branch banao, code plus tests likho, PR submit karo, review lo, revise karo, aur phir merge. Har step ka apna reason hai — jaise fork isliye taaki tum main project ko break kiye bina experiment kar sako.

Shuruaat ke liye pressure mat lo. Sabse easy entry point hota hai documentation fix — jaise note mein dikhaya gaya Scikit-learn ka max_features='sqrt' waala example, jaha tumhe zyada code likhne ki zaroorat nahi, par tumhe internals samajhne padte hain. Uske baad thoda intermediate level pe jaao — bug fixes, jaise PyTorch ka cosine_similarity waala 1D input crash. Yaha tum root cause diagnose karte ho aur ek clean fix likhte ho. Toh point yeh hai: chhote se shuru karo, consistency rakho, aur dheere-dheere tumhare commits hi tumhari sabse strong resume ban jaayenge. Give back to the community jisne tumhe seekhne ke tools diye!

Go deeper — visual, from zero

Test yourself — Research Frontiers & Practice

Connections