ストリーミング、Pandas、tiktoken を活用した NVIDIA Nemotron-Pretraining-Code-v3 メタデータからのコードデータセットパイプライン構築
本記事は、NVIDIA の大規模コードデータセットをダウンロードせずストリーミング処理で解析し、言語分布やリポジトリ頻度を可視化して効率的な学習用サンプルを構築する実用的なパイプライン構築法を提示している。
キーポイント
大規模データセットのストリーミング活用
NVIDIA Nemotron-Pretraining-Code-v3 のような数ギガバイト規模のデータセット全体をダウンロードせず、Hugging Face Datasets ライブラリのストリーミング機能を活用してメモリ効率よく処理する手法を紹介している。
コードメタデータの構造的解析
抽出したサンプルデータから、使用言語の分布、ファイル拡張子、リポジトリの頻度、ディレクトリ深度などを分析し、データセット全体の構造特性を把握するプロセスを示している。
実コードの再構築とトークン推定
メタデータから元の GitHub URL を復元してソースファイルをフェッチし、取得したコードのトークン規模を見積もることで、実際の学習リソース量を把握するワークフローを解説している。
再利用可能なフィルタリングサンプルの作成
分析結果に基づいて特定の条件でフィルタリングされたサンプルを作成し、後続の実験や研究に再利用できるよう処理済みデータを保存する最終ステップを記載している。
サンプリングと特徴量の抽出
ストリーミングデータからシャッフルされたサンプルを取得し、ファイル拡張子、ディレクトリ深度、ファイル名などのメタデータを抽出して分析します。
可視化によるデータ構造の理解
言語別、拡張子別、パス深さ、およびリポジトリ頻度のヒストグラムや棒グラフを作成し、データセット内の支配的なパターンを直感的に把握します。
生ファイルへのアクセス準備
メタデータから元の GitHub URL を再構築し、実際のソースコードファイルをフェッチするための基盤を整備しています。
影響分析・編集コメントを表示
影響分析
本記事は、大規模言語モデルの事前学習において一般的に問題となるデータセットの巨大さと処理コストという課題に対し、ストリーミング技術と効率的な分析手法を用いた解決策を提示しています。これにより、研究者やエンジニアがリソース制約の中で迅速にデータ特性を理解し、最適な学習用サブセットを構築するプロセスが標準化され、研究開発の効率向上に寄与します。
編集コメント
大規模モデル開発において、データの質と量を管理するための実用的なエンジニアリング手法が示されており、リソース効率を重視する現場の研究者にとって即戦力となる内容です。
本チュートリアルでは、コード事前学習研究のための大規模メタデータインデックスとして、NVIDIA の Nemotron-Pretraining-Code-v3 データセットを取り扱います。数ギガバイトに及ぶ完全なデータをダウンロードするのではなく、ストリーミングで取得し、そのスキーマを検証した上で、分析に適した管理可能なサンプルを構築します。その後、言語、ファイル拡張子、リポジトリの頻度、ディレクトリの深さを調査することでデータセットを探求し、インデックスがどのように構成されているかを理解します。次に、メタデータから生の GitHub URL を再構築し、実際のソースファイルをフェッチしようとして、取得されたコードのトークン規模を見積もります。ワークフローの終了時には、再利用可能なフィルタリング済みサンプルを作成し、さらなる実験のために処理済みの出力を保存します。
NVIDIA Nemotron-Pretraining-Code-v3 データセットのストリーミングとスキーマ検証
コードをコピーしました(Copied)
別のブラウザを使用してください
!pip -q install -U "datasets>=2.19" huggingface_hub tiktoken pyarrow 2>/dev/null
import os, io, time, itertools, collections, textwrap, math
import pandas as pd
import requests
import matplotlib.pyplot as plt
from datasets import load_dataset, get_dataset_config_names
REPO_ID = "nvidia/Nemotron-Pretraining-Code-v3"
pd.set_option("display.max_colwidth", 80)
configs = get_dataset_config_names(REPO_ID)
CONFIG = configs[0]
print(f"Configs available : {configs}")
print(f"Using config : {CONFIG}")
stream = load_dataset(REPO_ID, CONFIG, split="train", streaming=True)
print("\nFeatures / schema:")
print(stream.features)
print("\nFirst raw record:")
print(next(iter(stream)))
Colab 環境のセットアップとして、必要なライブラリのインストールと、データセットのストリーミング処理・分析・可視化に必要なツールのインポートを行いました。NVIDIA Nemotron-Pretraining-Code-v3 データセット ID を定義し、利用可能なデータセット構成を確認した後、トレーニング用スプリットをストリーミングモードで読み込みました。さらに、より深い分析を行う前にデータセットのスキーマを検索し、最初のレコードを出力して構造を理解しました。
シャッフルされたサンプルの構築とコードメタデータ特徴量の分析
コピー コピー済み別のブラウザを使用
N_SAMPLE = 30_000
shuffled = stream.shuffle(seed=42, buffer_size=20_000)
t0 = time.time()
rows = list(itertools.islice(shuffled, N_SAMPLE))
df = pd.DataFrame(rows)
print(f"\nPulled {len(df):,} rows in {time.time()-t0:,.1f}s")
print(df.head(10))
print("\nColumns:", list(df.columns), "| memory:",
f"{df.memory_usage(deep=True).sum()/1e6:,.1f} MB")
df["ext"] = df["rel_path"].str.extract(r"\.([A-Za-z0-9_]+)$")[0].str.lower()
df["depth"] = df["rel_path"].str.count("/")
df["fname"] = df["rel_path"].str.rsplit("/", n=1).str[-1]
print("\n--- Top 15 languages (sample) ---")
lang_counts = df["language"].value_counts()
print(lang_counts.head(15))
print("\n--- Top 15 file extensions (sample) ---")
print(df["ext"].value_counts().head(15))
print("\n--- Most frequent repositories (sample) ---")
print(df["repo"].value_counts().head(10))
print("\n--- Path-depth summary ---")
print(df["depth"].describe())
print(f"\nUnique repos in sample : {df['repo'].nunique():,}")
print(f"Unique languages : {df['language'].nunique():,}")
ストリーミングされたデータセットからシャッフルされたサンプルを作成することで、最初のクラスタリングされた行のみに依存しないようにします。サンプリングされたレコードを Pandas DataFrame(Python のデータ分析ライブラリ)に変換し、ファイル拡張子、パス深度、ファイル名などの有用な特徴量を導出します。その後、最も一般的な言語、ファイル拡張子、リポジトリ、およびパス深度の統計情報を調査することで、サンプルメタデータをより深く理解します。
言語、ファイル拡張子、ディレクトリ深度、およびリポジトリ頻度の可視化
コードをコピーしました。別のブラウザを使用してください
fig, ax = plt.subplots(2, 2, figsize=(14, 9))
lang_counts.head(12).iloc[::-1].plot.barh(ax=ax[0, 0], color="#76b900")
ax[0, 0].set_title("Top 12 languages (sample)"); ax[0, 0].set_xlabel("files")
df["ext"].value_counts().head(12).iloc[::-1].plot.barh(ax=ax[0, 1], color="#5b8def")
ax[0, 1].set_title("Top 12 file extensions (sample)"); ax[0, 1].set_xlabel("files")
df["depth"].clip(upper=12).plot.hist(bins=range(0, 14), ax=ax[1, 0],
color="#f4a261", edgecolor="white")
ax[1, 0].set_title("Directory nesting depth"); ax[1, 0].set_xlabel("'/' count in path")
(df["repo"].value_counts().head(10).iloc[::-1]
.plot.barh(ax=ax[1, 1], color="#9b5de5"))
ax[1, 1].set_title("Most common repos (sample)"); ax[1, 1].set_xlabel("files")
plt.tight_layout(); plt.show()
サンプルされたメタデータで見つかった主要なパターンを、複数のプロットを用いて可視化します。ここでは、上位の言語、上位のファイル拡張子、ディレクトリのネスト深度、および最も頻度の高いリポジトリを比較します。これらのチャートは、データセットの解釈を容易にし、メタデータインデックス内の支配的な構造を素早く特定するために使用されます。
生の GitHub URL の再構築と実ソースファイルの取得
コードをコピーしました。別のブラウザを使用してください
def raw_url(repo: str, commit_id: str, rel_path: str) -> str:
from urllib.parse import quote
return (f"https://raw.githubusercontent.com/{repo}/{commit_id}/"
f"{quote(rel_path)}")
df["raw_url"] = df.apply(lambda r: raw_url(r.repo, r.commit_id, r.rel_path), axis=1)
print("\nExample reconstructed URLs:")
for u in df["raw_url"].head(5):
print(" ", u)
def fetch_code(url: str, max_bytes: int = 200_000, timeout: int = 10):
try:
resp = requests.get(url, timeout=timeout)
if resp.status_code == 200 and len(resp.content) <= max_bytes:
return resp.text
return None
except requests.RequestException:
return None
print("\n--- Attempting to fetch a few real files ---")
fetched, attempts = [], 0
for _, r in df.sample(frac=1, random_state=1).iterrows():
if len(fetched) >= 5:
break
attempts += 1
code = fetch_code(r["raw_url"])
status = "OK " if code else "MISS"
print(f"[{status}] {r['language']:<12} {r['repo']}/{r['rel_path']}")
if code:
fetched.append({**r.to_dict(), "code": code, "n_chars": len(code)})
print(f"\nFetched {len(fetched)} files in {attempts} attempts "
f"(misses are normal — repos get deleted/renamed).")
if fetched:
ex = fetched[0]
print(f"\n----- PREVIEW: {ex['repo']}/{ex['rel_path']} ({ex['language']}) -----")
print(textwrap.shorten(ex["code"].replace("\n", " "), width=600,
placeholder=" ...[truncated]"))
メタデータからリポジトリ名、コミット ID、相対ファイルパスを用いて、生の GitHub URL を再構築します。その後、GitHub から実際のソースファイルを数件取得しようとし、存在しない、削除された、非公開の、またはサイズが大きすぎるファイルについては適切に処理します。正常に取得できたファイルのうち 1 つをプレビューし、メタデータインデックスが実際のコードコンテンツとどのように結びついているかを確認します。
Python ファイルのフィルタリング、トークン規模の見積もり、および出力の保存
コードをコピーしました(コピー済み)
別のブラウザを使用してください
TARGET_LANG = "Python"
py_index = df[df["language"] == TARGET_LANG].copy()
print(f"\n{TARGET_LANG} files in sample: {len(py_index):,}")
try:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
tok = lambda s: len(enc.encode(s, disallowed_special=()))
except Exception:
tok = lambda s: max(1, len(s) // 4)
if fetched:
toks = [tok(f["code"]) for f in fetched]
print(f"Fetched-file tokens: total={sum(toks):,} "
f"mean={sum(toks)/len(toks):,.0f}/file")
TOTAL_FILES, TOTAL_TOKENS = 146_323_609, 173e9
print(f"\nFull-dataset scale (per NVIDIA card): "
f"{TOTAL_FILES:,} files ≈ {TOTAL_TOKENS/1e9:.0f}B tokens "
f"(~{TOTAL_TOKENS/TOTAL_FILES:,.0f} tokens/file).")
df.to_parquet("nemotron_code_v3_sample.parquet", index=False)
if fetched:
pd.DataFrame(fetched).to_json("nemotron_fetched_code.jsonl",
orient="records", lines=True)
print("\nSaved: nemotron_code_v3_sample.parquet"
+ (", nemotron_fetched_code.jsonl" if fetched else ""))
print("Done
image")
サンプルされたインデックスから Python ファイルをフィルタリングし、正常に取得できたファイルのトークン数を推定します。利用可能な場合は tiktoken を使用し、利用できない場合は単純な文字ベースの推定値にフォールバックします。また、処理済みのメタデータ・サンプルと取得したコード出力を保存することで、後で再度データをストリーミングすることなく再利用できるようにしています。
結論
結論として、Nemotron-Pretraining-Code-v3 のメタデータインデックスを理解し活用するための実用的なエンドツーエンドのワークフローを構築しました。効率的にデータをストリーミングする方法、サンプルを DataFrame に変換する手順、探索的データ分析の実行、重要なパターンの可視化、リポジトリパスとコミット識別子から GitHub ファイル URL を再構築する方法について学びました。また、メタデータがソースコードまで遡って追跡可能であること、トークン推定がデータセットの規模感を把握する手がかりとなることも示しました。
ノートブック付きの完全なコードは こちらをご覧ください。Twitter で私たちをフォローすることもできますし、15 万人以上の ML サブレッドに参加したり、ニュースレターに登録することを忘れないでください。待ってください!Telegram を使っていますか?今なら Telegram でも私たちに参加できます。
GitHub リポジトリや Hugging Face ページ、製品リリース、ウェビナーなどのプロモーションのためにパートナーシップを希望される場合は、こちらからご連絡ください。
本記事「ストリーミング、Pandas、tiktoken を用いた NVIDIA Nemotron-Pretraining-Code-v3 メタデータからのコードデータセットパイプラインの構築」は、MarkTechPost で最初に公開されました。
原文を表示
In this tutorial, we work with NVIDIA’s Nemotron-Pretraining-Code-v3 dataset as a large-scale metadata index for code pretraining research. Instead of downloading the full multi-gigabyte dataset, we stream it, inspect its schema, and build a manageable sample for analysis. We then explore the dataset by studying languages, file extensions, repository frequency, and directory depth, which helps us understand how the index is structured. After that, we reconstruct the raw GitHub URLs from the metadata, attempt to fetch the actual source files, and estimate the token scale of the fetched code. By the end of the workflow, we create a reusable filtered sample and save processed outputs for further experimentation.
Streaming the NVIDIA Nemotron-Pretraining-Code-v3 Dataset and Inspecting Its Schema
Copy CodeCopiedUse a different Browser
!pip -q install -U "datasets>=2.19" huggingface_hub tiktoken pyarrow 2>/dev/null
import os, io, time, itertools, collections, textwrap, math
import pandas as pd
import requests
import matplotlib.pyplot as plt
from datasets import load_dataset, get_dataset_config_names
REPO_ID = "nvidia/Nemotron-Pretraining-Code-v3"
pd.set_option("display.max_colwidth", 80)
configs = get_dataset_config_names(REPO_ID)
CONFIG = configs[0]
print(f"Configs available : {configs}")
print(f"Using config : {CONFIG}")
stream = load_dataset(REPO_ID, CONFIG, split="train", streaming=True)
print("\nFeatures / schema:")
print(stream.features)
print("\nFirst raw record:")
print(next(iter(stream)))
We set up the Colab environment by installing the required libraries and importing the tools needed for dataset streaming, analysis, and visualization. We define the NVIDIA Nemotron-Pretraining-Code-v3 dataset ID, discover the available dataset configuration, and load the training split in streaming mode. We also inspect the dataset schema and print the first record to understand the structure before conducting deeper analysis.
Building a Shuffled Sample and Analyzing Code Metadata Features
Copy CodeCopiedUse a different Browser
N_SAMPLE = 30_000
shuffled = stream.shuffle(seed=42, buffer_size=20_000)
t0 = time.time()
rows = list(itertools.islice(shuffled, N_SAMPLE))
df = pd.DataFrame(rows)
print(f"\nPulled {len(df):,} rows in {time.time()-t0:,.1f}s")
print(df.head(10))
print("\nColumns:", list(df.columns), "| memory:",
f"{df.memory_usage(deep=True).sum()/1e6:,.1f} MB")
df["ext"] = df["rel_path"].str.extract(r"\.([A-Za-z0-9_]+)$")[0].str.lower()
df["depth"] = df["rel_path"].str.count("/")
df["fname"] = df["rel_path"].str.rsplit("/", n=1).str[-1]
print("\n--- Top 15 languages (sample) ---")
lang_counts = df["language"].value_counts()
print(lang_counts.head(15))
print("\n--- Top 15 file extensions (sample) ---")
print(df["ext"].value_counts().head(15))
print("\n--- Most frequent repositories (sample) ---")
print(df["repo"].value_counts().head(10))
print("\n--- Path-depth summary ---")
print(df["depth"].describe())
print(f"\nUnique repos in sample : {df['repo'].nunique():,}")
print(f"Unique languages : {df['language'].nunique():,}")
We create a shuffled sample from the streamed dataset so that we do not rely only on the first clustered rows. We convert the sampled records into a Pandas DataFrame and derive useful features such as file extension, path depth, and file name. We then examine the most common languages, file extensions, repositories, and path-depth statistics to better understand the sampled metadata.
Visualizing Languages, File Extensions, Directory Depth, and Repository Frequency
Copy CodeCopiedUse a different Browser
fig, ax = plt.subplots(2, 2, figsize=(14, 9))
lang_counts.head(12).iloc[::-1].plot.barh(ax=ax[0, 0], color="#76b900")
ax[0, 0].set_title("Top 12 languages (sample)"); ax[0, 0].set_xlabel("files")
df["ext"].value_counts().head(12).iloc[::-1].plot.barh(ax=ax[0, 1], color="#5b8def")
ax[0, 1].set_title("Top 12 file extensions (sample)"); ax[0, 1].set_xlabel("files")
df["depth"].clip(upper=12).plot.hist(bins=range(0, 14), ax=ax[1, 0],
color="#f4a261", edgecolor="white")
ax[1, 0].set_title("Directory nesting depth"); ax[1, 0].set_xlabel("'/' count in path")
(df["repo"].value_counts().head(10).iloc[::-1]
.plot.barh(ax=ax[1, 1], color="#9b5de5"))
ax[1, 1].set_title("Most common repos (sample)"); ax[1, 1].set_xlabel("files")
plt.tight_layout(); plt.show()
We visualize the main patterns found in the sampled metadata using multiple plots. We compare the top languages, top file extensions, directory nesting depth, and most frequent repositories in the sample. We use these charts to make the dataset easier to interpret and to quickly identify dominant structures inside the metadata index.
Reconstructing Raw GitHub URLs and Fetching Real Source Files
Copy CodeCopiedUse a different Browser
def raw_url(repo: str, commit_id: str, rel_path: str) -> str:
from urllib.parse import quote
return (f"https://raw.githubusercontent.com/{repo}/{commit_id}/"
f"{quote(rel_path)}")
df["raw_url"] = df.apply(lambda r: raw_url(r.repo, r.commit_id, r.rel_path), axis=1)
print("\nExample reconstructed URLs:")
for u in df["raw_url"].head(5):
print(" ", u)
def fetch_code(url: str, max_bytes: int = 200_000, timeout: int = 10):
try:
resp = requests.get(url, timeout=timeout)
if resp.status_code == 200 and len(resp.content) <= max_bytes:
return resp.text
return None
except requests.RequestException:
return None
print("\n--- Attempting to fetch a few real files ---")
fetched, attempts = [], 0
for _, r in df.sample(frac=1, random_state=1).iterrows():
if len(fetched) >= 5:
break
attempts += 1
code = fetch_code(r["raw_url"])
status = "OK " if code else "MISS"
print(f"[{status}] {r['language']:<12} {r['repo']}/{r['rel_path']}")
if code:
fetched.append({**r.to_dict(), "code": code, "n_chars": len(code)})
print(f"\nFetched {len(fetched)} files in {attempts} attempts "
f"(misses are normal — repos get deleted/renamed).")
if fetched:
ex = fetched[0]
print(f"\n----- PREVIEW: {ex['repo']}/{ex['rel_path']} ({ex['language']}) -----")
print(textwrap.shorten(ex["code"].replace("\n", " "), width=600,
placeholder=" ...[truncated]"))
We reconstruct raw GitHub URLs from the metadata: the repository name, commit ID, and relative file path. We then attempt to fetch a few real source files from GitHub, gracefully handling missing, deleted, private, or oversized files. We preview one successfully fetched file to see how the metadata index connects back to the actual code content.
Filtering Python Files, Estimating Token Scale, and Saving Outputs
Copy CodeCopiedUse a different Browser
TARGET_LANG = "Python"
py_index = df[df["language"] == TARGET_LANG].copy()
print(f"\n{TARGET_LANG} files in sample: {len(py_index):,}")
try:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
tok = lambda s: len(enc.encode(s, disallowed_special=()))
except Exception:
tok = lambda s: max(1, len(s) // 4)
if fetched:
toks = [tok(f["code"]) for f in fetched]
print(f"Fetched-file tokens: total={sum(toks):,} "
f"mean={sum(toks)/len(toks):,.0f}/file")
TOTAL_FILES, TOTAL_TOKENS = 146_323_609, 173e9
print(f"\nFull-dataset scale (per NVIDIA card): "
f"{TOTAL_FILES:,} files ≈ {TOTAL_TOKENS/1e9:.0f}B tokens "
f"(~{TOTAL_TOKENS/TOTAL_FILES:,.0f} tokens/file).")
df.to_parquet("nemotron_code_v3_sample.parquet", index=False)
if fetched:
pd.DataFrame(fetched).to_json("nemotron_fetched_code.jsonl",
orient="records", lines=True)
print("\nSaved: nemotron_code_v3_sample.parquet"
+ (", nemotron_fetched_code.jsonl" if fetched else ""))
print("Done
image")
We filter the sampled index for Python files and estimate token counts for successfully fetched files. We use tiktoken when available and fall back on a simple character-based estimate when it is not. Also, we save the processed metadata sample and the fetched code outputs so we can reuse them later without having to stream the dataset again.
Conclusion
In conclusion, we built a practical end-to-end workflow to understand and use the Nemotron-Pretraining-Code-v3 metadata index. We learned how to stream the dataset efficiently, convert a sample into a DataFrame, perform exploratory analysis, visualize important patterns, and reconstruct GitHub file URLs from repository paths and commit identifiers. We also demonstrated how metadata can be traced back to the source code and how token estimation provides a sense of dataset scale.
Check out the Full Codes with Notebook. Also, feel free to follow us on Twitter and don’t forget to join our 150k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.
Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us
The post Building a Code Dataset Pipeline from NVIDIA Nemotron-Pretraining-Code-v3 Metadata with Streaming, Pandas, and tiktoken appeared first on MarkTechPost.
関連記事
「スロッペンハイマー」:アマゾンの従業員が社内チャットで同社の AI を揶揄
アマゾン創業者のジェフ・ベゾスは AI が生産性を飛躍的に高めると信じているが、社内の従業員は AI ツールの出力を「ゴミ(スロップ)」と呼び、同社の動機付け策の失敗をジョークとして嘲笑している。
アップル、Google サーバー上で動作する AI でもプライバシー保護を維持と表明
アップルは、Siri の新機能「Siri AI」が Google の Gemini モデルおよび Nvidia ハードウェアを使用していることを確認したが、デバイス内または同社管理サーバーでの処理時と同様のプライバシー保護を保証すると発表した。
FrontierCode の紹介:高品質な生産データベース基準にモデルがどれだけ対応できるかを測定するベンチマーク
オープンソースのメンテナーらが作成した「FrontierCode」は、コードの結合可能性を初めて測定するベンチマークであり、敵対的テストや多段階レビューを含む厳格な QC パイプラインを通じて、モデルが高品質で保守可能なコードを書ける能力を示す最も強力な指標を提供します。
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み