RabbitDaisuke commited on
Commit
88ee5cb
·
verified ·
1 Parent(s): 195c7f6

Update browser execution-path benchmark 4a3dd2a174d10c99ba2a03166658a491f29b8754

Browse files
benchmark/README.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 実行性能と代替モデルの比較
2
+ この比較は、精度形式の名前だけで採用せず、必要な全身関節を維持したまま実行経路とモデルの選択を判断できるようにする。
3
+ ## RTMW3Dの実行経路
4
+ 標準NCHW、GPU入力・出力バッファ再利用NCHW、同NHWC、Graph Capture NHWCを同じ動画・モデル・正規化入力で比較する。標準FP32を固定基準にし、ほかの経路を自己比較して誤差ゼロにはしない。Graph CaptureではCPUフォールバックを無効にし、未対応の場合は失敗理由を残す。GPUバッファ再利用でも毎回入力を書き換え、座標を新しく読み戻す。GPU完了前のコマンド投入時間を推論完了時間として扱わない。
5
+ GPU timestamp profilingは別セッションで取得し、速度計測へ混ぜない。集計したカーネル時間にはCPU演算・転送・キュー待ちを含まない。通常版との比較は同じORT 1.27.0 JSEPのパッチ前後で行う。別実装のwebgpu-only版と混同しない。
6
+ 出典:https://onnxruntime.ai/docs/tutorials/web/performance-diagnosis.html
7
+ ## ネイティブGPU診断
8
+ ブラウザで「同じ入力を端末内へ保存」を選び、3枚の正規化済み入力を保存する。このファイルは画像内容を含むため端末内で使用する。通常の結果JSONへ画像や関節座標を含めない。同じFP32 ONNXと入力を、numpyとonnxruntime-gpuが利用できるGPU診断環境で比較する。GPUプロバイダーが利用できない場合にCPU計測へ置き換えない。
9
+ ```sh
10
+ python native_benchmark.py --model rtmw3d-l-fp32.onnx --input rtmw3d-native-inputs.f32 --provider cuda --iterations 200
11
+ ```
12
+ TensorRTを利用できる既存環境では`--provider tensorrt`を指定できる。これは性能診断用であり、ブラウザ推論の製品構成を変更しない。速度計測後、別セッションでGPU・CPUのノード割当てを記録する。
13
+ ## モデルを維持する条件と代替
14
+ 元モデル・実装:https://github.com/open-mmlab/mmpose
15
+ 公式のRTMW3D-L / X評価はCOCO-WholeBody AP 67.8 / 68.0、H3WB MPJPE 56 / 57mmである。異なる評価指標の差と実動画での足の追従品質を混同せず、1mm差から統計的な優位を主張しない。現在のRTMPose3Dモデル一覧ではLとXを確認した。
16
+ 出典:https://github.com/open-mmlab/mmpose/tree/main/projects/rtmpose3d
17
+ 全133点の相対3Dを維持する場合、RTMW3D-Lを比較基準として残す。腰・膝・足首・踵・足先の追跡を主目的とし、顔と指の詳細を不要にできる場合は、MediaPipe Poseの33点も比較できる。Holisticは33身体点に顔468点と左右各21手点を加えるため、Poseとの処理負荷を別に測る。座標契約が異なり、543点を共通座標系の133点3Dモデルと同一視しない。
18
+ 出典:https://developers.google.com/edge/mediapipe/solutions/vision/pose_landmarker
19
+ 出典:https://github.com/google-ai-edge/mediapipe/blob/master/docs/solutions/holistic.md
20
+ MediaPipe比較ページはPose / HolisticそれぞれLite / Fullを選択できる。Poseは0.5.1675469404、Holisticは0.5.1675471629の公式配布SDKに固定する。このHolistic JSではworld_landmarksが`za`という短縮名で返ることを配布ソースで確認し、その版だけ明示的に対応する。身体33点、足6点の可視性、world33点の取得率も記録する。未検出による見かけの高fpsを追跡成功にしない。検出・追跡を含むパイプライン全体の時間なので、人物検出を含まないRTMW3Dモデル単体とは測定範囲が異なる。三つの静止時点の反復は、連続動画の揺れ・遮蔽復帰・距離精度の検証ではない。
21
+ 複数台の同期・内部外部校正・共通関節の三角測量を行う場合は、各視点の軽量2Dモデルも候補にできる。RTMPose Halpe26は足首と足部を含み、公式256×192版のt / s / mはそれぞれ3.51 / 5.70 / 13.93Mパラメーター、0.37 / 0.70 / 1.95GFLOPsである。WebGPU速度と足の品質は別途実測する。単眼の2D結果だけで前後移動や足の3D姿勢が完成したとは扱わない。
22
+ 出典:https://github.com/open-mmlab/mmpose/blob/main/configs/body_2d_keypoint/rtmpose/body8/rtmpose_body8-halpe26.md
benchmark/benchmark.js CHANGED
@@ -1,7 +1,7 @@
1
  import {MODES,GROUPS,percentile as pct,compare,qualityGate,createExecution,summarizeProfile} from './execution.js';
2
  const $=id=>document.getElementById(id),REPO='RabbitDaisuke/rtmw3d-webgpu-onnx';
3
  const video=$('video'),crop=$('crop'),ctx=crop.getContext('2d',{willReadFrequently:true});
4
- let catalog,revision,base,ort,stopped=false,results=[],videoURL,runContext;
5
  const runtimes=new Map();
6
  const status=s=>$('status').textContent=s;
7
  async function hash(bytes){return [...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(x=>x.toString(16).padStart(2,'0')).join('');}
@@ -55,7 +55,7 @@ async function profile(runtime,data,mode,inputs){
55
  }finally{if(runner)await runner.release();runtime.env.webgpu.profiling={mode:'off',ondata:()=>{}};}
56
  }
57
  async function measure(){
58
- stopped=false;results=[];render();$('start').disabled=true;$('stop').disabled=false;$('download').disabled=true;
59
  try{
60
  const selected=[...document.querySelectorAll('#models input:checked')].map(x=>x.value),set=new Set(selected);
61
  for(const id of selected){const family=catalog.variants.find(v=>v.id===id).model;set.add(family+'-fp32');}
@@ -64,6 +64,7 @@ async function measure(){
64
  if(!selected.length||!requestedModes.length)throw Error('モデルと実行経路を選択してください');
65
  const modes=MODES.filter(m=>m.id==='standard'||requestedModes.includes(m.id));
66
  const runtime=await loadRuntime(),inputs=await sampleInputs(),reference=new Map(),views=Number($('views').value),iterations=Math.max(12,Math.min(1000,Number($('iterations').value)||200));
 
67
  runContext={source:{width:video.videoWidth,height:video.videoHeight,duration:video.duration},inputShape:[1,3,384,288],sampleFractions:[.2,.5,.8],roiPercent:Object.fromEntries(['x','y','w','h'].map(k=>[k,Number($(k).value)])),views,iterations,warmupRuns:5};
68
  for(const variant of variants){
69
  if(stopped)break;const data=await bytes(variant.file,variant.sha256);
@@ -101,6 +102,7 @@ async function measure(){
101
  $('video-file').onchange=e=>{if(!e.target.files[0])return;if(videoURL)URL.revokeObjectURL(videoURL);videoURL=URL.createObjectURL(e.target.files[0]);video.src=videoURL;video.load();};
102
  $('start').onclick=measure;$('stop').onclick=()=>{stopped=true;};
103
  $('download').onclick=()=>{const data={schema:'rtmw3d-gpu-comparison/v2',createdAt:new Date().toISOString(),source:runContext?.source,runContext,results,notes:['All variants output all 133 joints','Differences are relative to the architecture FP32 standard-path result, not ground truth','Timings include input upload, GPU completion and fresh 133-joint CPU readback','GPU timestamp profiling uses a separate session and is excluded from speed measurements','requestedBackend is the requested provider; it does not prove that every node ran on GPU','1–4 inputs measure a shared-session workload, not synchronized physical cameras','GPU utilization, VRAM, device identity, video names and video contents are not exported']};const u=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=u;a.download='rtmw3d-fullbody-gpu-comparison.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);};
 
104
  try{
105
  const model=await(await get(`https://huggingface.co/api/models/${REPO}`)).json();revision=model.sha;base=`https://huggingface.co/${REPO}/resolve/${revision}/`;catalog=await(await get(base+'models.json')).json();
106
  if(catalog.keypointCount!==133)throw Error('全身133点のカタログではありません');$('models').replaceChildren();
 
1
  import {MODES,GROUPS,percentile as pct,compare,qualityGate,createExecution,summarizeProfile} from './execution.js';
2
  const $=id=>document.getElementById(id),REPO='RabbitDaisuke/rtmw3d-webgpu-onnx';
3
  const video=$('video'),crop=$('crop'),ctx=crop.getContext('2d',{willReadFrequently:true});
4
+ let catalog,revision,base,ort,stopped=false,results=[],videoURL,runContext,preparedInputs;
5
  const runtimes=new Map();
6
  const status=s=>$('status').textContent=s;
7
  async function hash(bytes){return [...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(x=>x.toString(16).padStart(2,'0')).join('');}
 
55
  }finally{if(runner)await runner.release();runtime.env.webgpu.profiling={mode:'off',ondata:()=>{}};}
56
  }
57
  async function measure(){
58
+ stopped=false;results=[];render();$('start').disabled=true;$('stop').disabled=false;$('download').disabled=true;$('native-input').disabled=true;
59
  try{
60
  const selected=[...document.querySelectorAll('#models input:checked')].map(x=>x.value),set=new Set(selected);
61
  for(const id of selected){const family=catalog.variants.find(v=>v.id===id).model;set.add(family+'-fp32');}
 
64
  if(!selected.length||!requestedModes.length)throw Error('モデルと実行経路を選択してください');
65
  const modes=MODES.filter(m=>m.id==='standard'||requestedModes.includes(m.id));
66
  const runtime=await loadRuntime(),inputs=await sampleInputs(),reference=new Map(),views=Number($('views').value),iterations=Math.max(12,Math.min(1000,Number($('iterations').value)||200));
67
+ preparedInputs=inputs;$('native-input').disabled=false;
68
  runContext={source:{width:video.videoWidth,height:video.videoHeight,duration:video.duration},inputShape:[1,3,384,288],sampleFractions:[.2,.5,.8],roiPercent:Object.fromEntries(['x','y','w','h'].map(k=>[k,Number($(k).value)])),views,iterations,warmupRuns:5};
69
  for(const variant of variants){
70
  if(stopped)break;const data=await bytes(variant.file,variant.sha256);
 
102
  $('video-file').onchange=e=>{if(!e.target.files[0])return;if(videoURL)URL.revokeObjectURL(videoURL);videoURL=URL.createObjectURL(e.target.files[0]);video.src=videoURL;video.load();};
103
  $('start').onclick=measure;$('stop').onclick=()=>{stopped=true;};
104
  $('download').onclick=()=>{const data={schema:'rtmw3d-gpu-comparison/v2',createdAt:new Date().toISOString(),source:runContext?.source,runContext,results,notes:['All variants output all 133 joints','Differences are relative to the architecture FP32 standard-path result, not ground truth','Timings include input upload, GPU completion and fresh 133-joint CPU readback','GPU timestamp profiling uses a separate session and is excluded from speed measurements','requestedBackend is the requested provider; it does not prove that every node ran on GPU','1–4 inputs measure a shared-session workload, not synchronized physical cameras','GPU utilization, VRAM, device identity, video names and video contents are not exported']};const u=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=u;a.download='rtmw3d-fullbody-gpu-comparison.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);};
105
+ $('native-input').onclick=()=>{if(!preparedInputs)return;if(new Uint8Array(new Uint32Array([1]).buffer)[0]!==1)throw Error('この端末ではlittle-endian入力を保存できません');const url=URL.createObjectURL(new Blob(preparedInputs,{type:'application/octet-stream'})),a=document.createElement('a');a.href=url;a.download='rtmw3d-native-inputs.f32';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
106
  try{
107
  const model=await(await get(`https://huggingface.co/api/models/${REPO}`)).json();revision=model.sha;base=`https://huggingface.co/${REPO}/resolve/${revision}/`;catalog=await(await get(base+'models.json')).json();
108
  if(catalog.keypointCount!==133)throw Error('全身133点のカタログではありません');$('models').replaceChildren();
benchmark/index.html CHANGED
@@ -1,6 +1,7 @@
1
  <!doctype html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>全身RTMW3D · GPU比較</title><style>
2
  *{box-sizing:border-box}body{max-width:1280px;margin:32px auto;padding:0 22px;background:#f5f5f0;color:#20352c;font:14px/1.7 system-ui,sans-serif}h1{font-size:26px}section{background:#fff;border:1px solid #dce4d8;border-radius:9px;padding:20px;margin:16px 0}button,select,input{font:inherit;padding:8px}button{background:#194f40;color:white;border:0;border-radius:5px;cursor:pointer}button:disabled{opacity:.4;cursor:default}label{display:inline-flex;gap:7px;align-items:center;margin:6px 18px 6px 0}input[type=number]{width:76px;border:1px solid #cbd5c5;border-radius:4px}video{max-height:280px;width:100%;background:#102a23}table{border-collapse:collapse;width:100%;font-size:12px}td,th{padding:9px;border-bottom:1px solid #e3e8df;text-align:left}#models{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr))}#status{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px}small{color:#718168}a{color:#286951}.table-wrap{overflow-x:auto}.bad{color:#a04c33}canvas{display:none}.note{font-size:12px;color:#6e7f65}</style><script type="module" src="./benchmark.js"></script></head><body>
3
  <h1>足首・足先を含む全身RTMW3DのWebGPU比較</h1><p>全候補は133点を保持します。同じモデルと動画入力で、数値形式・GPUメモリ再利用・実行経路を比較します。</p><p class="note">1〜4入力は1セッションを時分割する推論負荷です。物理カメラの同期・三角測量・SteamVR送出の実測ではありません。映像は端末から送信しません。</p><label><input id="original" type="checkbox" checked>FP32で未パッチJSEP版の標準経路も比較する</label><p class="note">同じORT 1.27.0 JSEPのパッチ前後を比較します。別実装のwebgpu-only配布物とは区別します。</p>
 
4
  <section><h2>1. ローカル動画と人物範囲</h2><input id="video-file" type="file" accept="video/*"><video id="video" controls playsinline muted></video><div><label>ROI左 % <input id="x" type="number" value="0" min="0" max="99"></label><label>ROI上 % <input id="y" type="number" value="0" min="0" max="99"></label><label>ROI幅 % <input id="w" type="number" value="100" min="1" max="100"></label><label>ROI高 % <input id="h" type="number" value="100" min="1" max="100"></label></div><small>全身と足先が入る範囲を指定してください。3時刻の同じROIを各モデルで使用します。解像度はモデル入力288×384にだけ変換します。</small></section>
5
  <section><h2>2. 比較候補</h2><div id="models">カタログ取得中…</div><p class="note">同じLまたはXのFP32基準も自動で測定します。FP32との差は正解データに対する精度ではありません。初回は選択したモデルだけ取得・キャッシュします。</p><h2>3. 実行経路</h2><div id="modes"></div><p class="note">標準経路も基準として自動測定します。GPUバッファ再利用とGraph Captureも、入力転送・GPU完了・133関節の読戻しを含めて測ります。Graph Captureで未対応演算があれば失敗理由を記録します。差分基準は身体・股関節・膝・足首・足先それぞれXY p95 ≤ 3px、Z p95 ≤ 5cm、信頼度低下なしです。観測不足では合格にしません。</p><label><input id="profile" type="checkbox" checked>計測後に別セッションで演算別GPU診断を記録</label><p class="note">診断にはtimestamp-queryが必要です。診断時の負荷は速度計測へ含めません。JSONに動画名・映像・端末識別情報は保存しません。</p><label>入力相当数 <select id="views"><option>1</option><option>2</option><option>3</option><option>4</option></select></label><label>計測推論回数 <input id="iterations" type="number" value="200" min="12" max="1000"></label><button id="start" disabled>選択した全身モデルを比較</button> <button id="stop" disabled>停止</button> <button id="download" disabled>結果JSON</button><pre id="status" role="status"></pre></section>
6
  <section class="table-wrap"><table><thead><tr><th>全身モデル</th><th>実行経路</th><th>容量 MB</th><th>p50 / p95 ms</th><th>合計fps</th><th>入力あたりfps</th><th>身体・足 XY / Z p95</th><th>足首 XY / Z p95</th><th>足先 XY / Z p95</th><th>判定</th></tr></thead><tbody id="results"></tbody></table></section><p><a href="https://github.com/open-mmlab/mmpose" target="_blank" rel="noreferrer">元モデル:OpenMMLab MMPose</a> · <a href="https://huggingface.co/RabbitDaisuke/rtmw3d-webgpu-onnx" target="_blank" rel="noreferrer">モデル・比較レポート</a></p><canvas id="crop" width="288" height="384"></canvas></body></html>
 
1
  <!doctype html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>全身RTMW3D · GPU比較</title><style>
2
  *{box-sizing:border-box}body{max-width:1280px;margin:32px auto;padding:0 22px;background:#f5f5f0;color:#20352c;font:14px/1.7 system-ui,sans-serif}h1{font-size:26px}section{background:#fff;border:1px solid #dce4d8;border-radius:9px;padding:20px;margin:16px 0}button,select,input{font:inherit;padding:8px}button{background:#194f40;color:white;border:0;border-radius:5px;cursor:pointer}button:disabled{opacity:.4;cursor:default}label{display:inline-flex;gap:7px;align-items:center;margin:6px 18px 6px 0}input[type=number]{width:76px;border:1px solid #cbd5c5;border-radius:4px}video{max-height:280px;width:100%;background:#102a23}table{border-collapse:collapse;width:100%;font-size:12px}td,th{padding:9px;border-bottom:1px solid #e3e8df;text-align:left}#models{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr))}#status{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px}small{color:#718168}a{color:#286951}.table-wrap{overflow-x:auto}.bad{color:#a04c33}canvas{display:none}.note{font-size:12px;color:#6e7f65}</style><script type="module" src="./benchmark.js"></script></head><body>
3
  <h1>足首・足先を含む全身RTMW3DのWebGPU比較</h1><p>全候補は133点を保持します。同じモデルと動画入力で、数値形式・GPUメモリ再利用・実行経路を比較します。</p><p class="note">1〜4入力は1セッションを時分割する推論負荷です。物理カメラの同期・三角測量・SteamVR送出の実測ではありません。映像は端末から送信しません。</p><label><input id="original" type="checkbox" checked>FP32で未パッチJSEP版の標準経路も比較する</label><p class="note">同じORT 1.27.0 JSEPのパッチ前後を比較します。別実装のwebgpu-only配布物とは区別します。</p>
4
+ <p><a href="./mediapipe.html">MediaPipe Pose / Holistic比較</a> · <a href="./native_benchmark.py" download>ネイティブGPU診断スクリプト</a></p><p><button id="native-input" disabled>同じ入力を端末内へ保存</button> <small>ネイティブ比較用。正規化済みの画像3枚を含む診断ファイルです。端末内でのみ使用してください。通常の結果JSONには画像を含みません。</small></p>
5
  <section><h2>1. ローカル動画と人物範囲</h2><input id="video-file" type="file" accept="video/*"><video id="video" controls playsinline muted></video><div><label>ROI左 % <input id="x" type="number" value="0" min="0" max="99"></label><label>ROI上 % <input id="y" type="number" value="0" min="0" max="99"></label><label>ROI幅 % <input id="w" type="number" value="100" min="1" max="100"></label><label>ROI高 % <input id="h" type="number" value="100" min="1" max="100"></label></div><small>全身と足先が入る範囲を指定してください。3時刻の同じROIを各モデルで使用します。解像度はモデル入力288×384にだけ変換します。</small></section>
6
  <section><h2>2. 比較候補</h2><div id="models">カタログ取得中…</div><p class="note">同じLまたはXのFP32基準も自動で測定します。FP32との差は正解データに対する精度ではありません。初回は選択したモデルだけ取得・キャッシュします。</p><h2>3. 実行経路</h2><div id="modes"></div><p class="note">標準経路も基準として自動測定します。GPUバッファ再利用とGraph Captureも、入力転送・GPU完了・133関節の読戻しを含めて測ります。Graph Captureで未対応演算があれば失敗理由を記録します。差分基準は身体・股関節・膝・足首・足先それぞれXY p95 ≤ 3px、Z p95 ≤ 5cm、信頼度低下なしです。観測不足では合格にしません。</p><label><input id="profile" type="checkbox" checked>計測後に別セッションで演算別GPU診断を記録</label><p class="note">診断にはtimestamp-queryが必要です。診断時の負荷は速度計測へ含めません。JSONに動画名・映像・端末識別情報は保存しません。</p><label>入力相当数 <select id="views"><option>1</option><option>2</option><option>3</option><option>4</option></select></label><label>計測推論回数 <input id="iterations" type="number" value="200" min="12" max="1000"></label><button id="start" disabled>選択した全身モデルを比較</button> <button id="stop" disabled>停止</button> <button id="download" disabled>結果JSON</button><pre id="status" role="status"></pre></section>
7
  <section class="table-wrap"><table><thead><tr><th>全身モデル</th><th>実行経路</th><th>容量 MB</th><th>p50 / p95 ms</th><th>合計fps</th><th>入力あたりfps</th><th>身体・足 XY / Z p95</th><th>足首 XY / Z p95</th><th>足先 XY / Z p95</th><th>判定</th></tr></thead><tbody id="results"></tbody></table></section><p><a href="https://github.com/open-mmlab/mmpose" target="_blank" rel="noreferrer">元モデル:OpenMMLab MMPose</a> · <a href="https://huggingface.co/RabbitDaisuke/rtmw3d-webgpu-onnx" target="_blank" rel="noreferrer">モデル・比較レポート</a></p><canvas id="crop" width="288" height="384"></canvas></body></html>
benchmark/mediapipe-adapter.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ // Verified in the pinned 0.5.1675471629 SDK: world_landmarks is exposed as
2
+ // the minified field `za`, while pose.d.ts exposes poseWorldLandmarks normally.
3
+ export function poseWorldResult(result,kind,version){
4
+ if(result.poseWorldLandmarks)return {points:result.poseWorldLandmarks,field:'poseWorldLandmarks'};
5
+ if(kind==='holistic'&&version==='0.5.1675471629'&&Array.isArray(result.za))return {points:result.za,field:'za'};
6
+ return {points:[],field:null};
7
+ }
benchmark/mediapipe.html ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <!doctype html><html lang="ja"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>全身トラッキング · MediaPipe比較</title><style>
2
+ *{box-sizing:border-box}body{max-width:1200px;margin:32px auto;padding:0 22px;background:#f5f5f0;color:#20352c;font:14px/1.7 system-ui,sans-serif}section{background:white;border:1px solid #dce4d8;border-radius:9px;padding:20px;margin:16px 0}button,input,select{font:inherit;padding:8px}button{background:#194f40;color:white;border:0;border-radius:5px;cursor:pointer}button:disabled{opacity:.4}label{display:inline-flex;gap:7px;align-items:center;margin:6px 18px 6px 0}input[type=number]{width:76px}video{width:100%;max-height:280px;background:#102a23}table{width:100%;border-collapse:collapse;font-size:12px}td,th{padding:9px;border-bottom:1px solid #e3e8df;text-align:left}small{color:#6e7f65}a{color:#286951}.table-wrap{overflow-x:auto}.bad{color:#a04c33}#status{white-space:pre-wrap;overflow-wrap:anywhere}</style><script type="module" src="./mediapipe.js"></script></head><body>
3
+ <h1>MediaPipe Pose / Holisticの全身比較</h1><p><a href="./">RTMW3Dの実行経路比較へ戻る</a></p><p>足首・踵・足先を含む33点の身体推定と、顔・手も処理するHolisticを比較します。初回に公開SDKとモデルを取得します。動画・姿勢データは外部へ送信しません。</p>
4
+ <section><h2>1. 同じローカル動画と人物範囲</h2><input id="video-file" type="file" accept="video/*"><video id="video" controls playsinline muted></video><label>ROI左 % <input id="x" type="number" value="0" min="0" max="99"></label><label>ROI上 % <input id="y" type="number" value="0" min="0" max="99"></label><label>ROI幅 % <input id="w" type="number" value="100" min="1" max="100"></label><label>ROI高 % <input id="h" type="number" value="100" min="1" max="100"></label><p><small>RTMW3D比較と同じ動画・ROIを指定してください。同じ20%・50%・80%の3時刻を288×384へ切り抜いて反復します。連続動作の安定性検証ではありません。</small></p></section>
5
+ <section><h2>2. 比較対象</h2><div id="models"><label><input type="checkbox" value="pose:0">Pose Lite</label><label><input type="checkbox" value="pose:1" checked>Pose Full</label><label><input type="checkbox" value="holistic:0">Holistic Lite</label><label><input type="checkbox" value="holistic:1" checked>Holistic Full</label></div><p><small>Pose SDK 0.5.1675469404 / Holistic SDK 0.5.1675471629を固定。顔・手を含むHolisticは543点構成で、133点と同じ骨格・座標契約ではありません。使用SDKがworld座標を返さない場合は「取得なし」と表示します。33点のworld座標も腰を原点とする推定値で、部屋内の絶対位置ではありません。</small></p><label>入力相当数 <select id="views"><option>1</option><option>2</option><option>3</option><option>4</option></select></label><label>計測回数 <input id="iterations" type="number" value="200" min="12" max="1000"></label><button id="start">選択した構成を比較</button> <button id="stop" disabled>停止</button> <button id="download" disabled>結果JSON</button><p><small>検出・追跡・姿勢推定を含むパイプライン全体の時間です。人物検出を含まないRTMW3D単体とは測定範囲が異なります。未検出時の速さを追跡成功として扱いません。</small></p><pre id="status" role="status"></pre></section>
6
+ <section class="table-wrap"><table><thead><tr><th>構成</th><th>p50 / p95 ms</th><th>合計fps</th><th>入力あたりfps</th><th>身体33点取得</th><th>足6点可視</th><th>world33点取得</th><th>状態</th></tr></thead><tbody id="results"></tbody></table></section><p><a href="https://developers.google.com/edge/mediapipe/solutions/vision/pose_landmarker">MediaPipe Pose公式</a> · <a href="https://github.com/google-ai-edge/mediapipe/blob/master/docs/solutions/holistic.md">Holistic公式</a></p></body></html>
benchmark/mediapipe.js ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {poseWorldResult} from './mediapipe-adapter.js';
2
+ const $=id=>document.getElementById(id),video=$('video');
3
+ const packages={pose:{version:'0.5.1675469404',global:'Pose'},holistic:{version:'0.5.1675471629',global:'Holistic'}};
4
+ const sources=new Map();let busy=false,stopped=false,rows=[],context,videoURL;
5
+ const pct=(a,p)=>{const s=[...a].sort((x,y)=>x-y);return s.length?s[Math.floor((s.length-1)*p)]:null;};
6
+ const status=s=>$('status').textContent=s;
7
+ async function load(kind){
8
+ if(sources.has(kind))return sources.get(kind);
9
+ const spec=packages[kind],base=`https://cdn.jsdelivr.net/npm/@mediapipe/${kind}@${spec.version}/`;
10
+ await new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=base+kind+'.js';script.crossOrigin='anonymous';script.referrerPolicy='no-referrer';script.onload=resolve;script.onerror=()=>reject(Error('MediaPipeスクリプトの取得に失敗'));document.head.append(script);});
11
+ const result={Class:globalThis[spec.global],base,version:spec.version};if(!result.Class)throw Error('MediaPipeクラスが見つかりません');sources.set(kind,result);return result;
12
+ }
13
+ async function seek(time){if(Math.abs(video.currentTime-time)<.001&&video.readyState>=2)return;await new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(Error('動画のシークに失敗')),15000);video.addEventListener('seeked',()=>{clearTimeout(timer);resolve();},{once:true});video.currentTime=time;});}
14
+ async function samples(){
15
+ if(!video.videoWidth)throw Error('ローカル動画を選択してください');video.pause();
16
+ const frames=[],x=Number($('x').value)/100*video.videoWidth,y=Number($('y').value)/100*video.videoHeight;
17
+ let w=Number($('w').value)/100*video.videoWidth,h=Number($('h').value)/100*video.videoHeight;
18
+ if(w<=0||h<=0)throw Error('ROIサイズが不正です');const cx=x+w/2,cy=y+h/2;if(w/h>.75)h=w/.75;else w=h*.75;
19
+ for(const f of[.2,.5,.8]){
20
+ await seek(Math.min(video.duration-.01,video.duration*f));const canvas=document.createElement('canvas');canvas.width=288;canvas.height=384;const ctx=canvas.getContext('2d');
21
+ ctx.fillStyle='black';ctx.fillRect(0,0,288,384);ctx.setTransform(288/w,0,0,384/h,-(cx-w/2)*288/w,-(cy-h/2)*384/h);ctx.drawImage(video,0,0);frames.push(canvas);
22
+ }return frames;
23
+ }
24
+ function render(){
25
+ $('results').replaceChildren();for(const row of rows){const tr=document.createElement('tr'),m=row.metrics;
26
+ for(const v of[row.id,m?`${m.p50Ms.toFixed(2)} / ${m.p95Ms.toFixed(2)}`:'—',m?m.aggregateFPS.toFixed(1):'—',m?m.perInputFPS.toFixed(1):'—',`${row.poseFoundFrames??0}/${row.measuredFrames??0}`,`${row.feetVisibleFrames??0}/${row.measuredFrames??0}`,row.worldFoundFrames?`${row.worldFoundFrames}/${row.measuredFrames}`:'取得なし',row.error||'計測完了']){const td=document.createElement('td');td.textContent=v;tr.append(td);}if(row.error||!row.poseFoundFrames)tr.className='bad';$('results').append(tr);
27
+ }
28
+ }
29
+ $('video-file').onchange=e=>{if(!e.target.files[0])return;if(videoURL)URL.revokeObjectURL(videoURL);videoURL=URL.createObjectURL(e.target.files[0]);video.src=videoURL;video.load();};
30
+ $('start').onclick=async()=>{
31
+ if(busy)return;busy=true;stopped=false;rows=[];render();$('start').disabled=true;$('stop').disabled=false;$('download').disabled=true;
32
+ try{
33
+ const frames=await samples(),iterations=Math.max(12,Math.min(1000,Number($('iterations').value)||200)),views=Number($('views').value);
34
+ context={source:{width:video.videoWidth,height:video.videoHeight,duration:video.duration},roiPercent:Object.fromEntries(['x','y','w','h'].map(k=>[k,Number($(k).value)])),sampleFractions:[.2,.5,.8],inputCanvas:[288,384],iterations,views};
35
+ const choices=[...document.querySelectorAll('#models input:checked')].map(i=>i.value);
36
+ if(!choices.length)throw Error('比較候補を選択してください');
37
+ for(const id of choices){
38
+ if(stopped)break;const [kind,complexity]=id.split(':'),record={id:kind+'-'+(complexity==='0'?'lite':'full'),requestedBackend:'MediaPipe GPU delegate',backendVerified:false,packageVersion:packages[kind].version,views,poseFoundFrames:0,feetVisibleFrames:0,worldFoundFrames:0,measuredFrames:0};rows.push(record);let model,lastResult;
39
+ try{
40
+ status(`初期化: ${record.id}`);const module=await load(kind);model=new module.Class({locateFile:file=>module.base+file});
41
+ model.setOptions({modelComplexity:Number(complexity),useCpuInference:false,smoothLandmarks:false,enableSegmentation:false,smoothSegmentation:false,refineFaceLandmarks:false,minDetectionConfidence:.5,minTrackingConfidence:.5});
42
+ model.onResults(result=>{lastResult=result;});await model.initialize();
43
+ const run=async frame=>{lastResult=null;await model.send({image:frame});if(!lastResult)throw Error('MediaPipe結果コールバックが返りません');return lastResult;};
44
+ for(let i=0;i<5;i++)await run(frames[i%frames.length]);
45
+ const times=[],started=performance.now();status(`計測: ${record.id}`);
46
+ for(let i=0;i<iterations&&!stopped;i++){
47
+ const begin=performance.now(),result=await run(frames[i%frames.length]);times.push(performance.now()-begin);record.measuredFrames++;
48
+ const points=result.poseLandmarks??[],worldResult=poseWorldResult(result,kind,packages[kind].version),world=worldResult.points;record.worldResultField=worldResult.field;
49
+ if(points.length===33&&points.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))){record.poseFoundFrames++;if([27,28,29,30,31,32].every(j=>(points[j].visibility??0)>=.3))record.feetVisibleFrames++;}
50
+ if(world.length===33&&world.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y)&&Number.isFinite(p.z)))record.worldFoundFrames++;
51
+ record.lastOutputCounts={pose:points.length,world:world.length,face:result.faceLandmarks?.length??0,leftHand:result.leftHandLandmarks?.length??0,rightHand:result.rightHandLandmarks?.length??0};
52
+ }
53
+ const wallMs=performance.now()-started;record.interrupted=stopped;
54
+ if(times.length)record.metrics={p50Ms:pct(times,.5),p95Ms:pct(times,.95),aggregateFPS:times.length/wallMs*1000,perInputFPS:times.length/wallMs*1000/views,wallMs,actualInferences:times.length,sessionTimesMs:times};
55
+ record.trackingUsable=record.measuredFrames>0&&record.poseFoundFrames===record.measuredFrames&&record.feetVisibleFrames===record.measuredFrames;
56
+ }catch(error){record.error=String(error.message||error);}finally{if(model)await model.close().catch(()=>{});render();}
57
+ }status(stopped?'停止しました':'計測完了。追跡率とworld座標の取得有無を速度と併せて確認してください。');$('download').disabled=false;
58
+ }catch(error){status(String(error.message||error));}finally{busy=false;$('start').disabled=false;$('stop').disabled=true;}
59
+ };
60
+ $('stop').onclick=()=>{stopped=true;};
61
+ $('download').onclick=()=>{
62
+ const report={schema:'mediapipe-fullbody-comparison/v1',createdAt:new Date().toISOString(),context,results:rows,notes:['Local video only; video contents, names and landmark coordinates are not exported','Same three sampled crops are repeated; this is not a continuous-motion jitter or accuracy test','Includes MediaPipe detection/tracking/pose and optional face/hand pipeline; RTMW3D timings exclude person detection','GPU delegate is requested but individual kernel placement is not profiled','33-point pose topology includes ankles, heels and foot-index landmarks','World coordinates, when available, are hip-relative model estimates, not calibrated room position','Pinned Holistic 0.5.1675471629 world_landmarks output is read from its source-verified minified za field; missing data is never fabricated','Detection failure can produce misleadingly high FPS: inspect pose/foot coverage']};
63
+ const url=URL.createObjectURL(new Blob([JSON.stringify(report,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='mediapipe-fullbody-comparison.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
64
+ };
benchmark/native_benchmark.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPU diagnosis only: reuse the browser's exact FP32 model and normalized inputs."""
2
+ import argparse
3
+ from collections import defaultdict
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import tempfile
8
+ import time
9
+
10
+ import numpy as np
11
+ import onnxruntime as ort
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument('--model', type=Path, required=True)
17
+ parser.add_argument('--input', type=Path, required=True, help='Browser-exported little-endian float32 .f32 file')
18
+ parser.add_argument('--provider', choices=['cuda', 'tensorrt'], default='cuda')
19
+ parser.add_argument('--iterations', type=int, default=200)
20
+ parser.add_argument('--views', type=int, choices=range(1, 5), default=1)
21
+ parser.add_argument('--output', type=Path, default=Path('rtmw3d-native-comparison.json'))
22
+ args = parser.parse_args()
23
+ provider = {'cuda': 'CUDAExecutionProvider', 'tensorrt': 'TensorrtExecutionProvider'}[args.provider]
24
+ if provider not in ort.get_available_providers():
25
+ raise RuntimeError(f'{provider} is unavailable; no CPU performance substitute is allowed')
26
+ if not 12 <= args.iterations <= 1000:
27
+ raise ValueError('iterations must be between 12 and 1000')
28
+ data = np.fromfile(args.input, dtype='<f4')
29
+ elements = 3 * 384 * 288
30
+ if data.size != 3 * elements or not np.isfinite(data).all():
31
+ raise ValueError('Expected the exact three finite [1,3,384,288] browser inputs')
32
+ samples = data.reshape(3, 1, 3, 384, 288).astype(np.float32)
33
+ providers = [(provider, {'trt_fp16_enable': False})] if args.provider == 'tensorrt' else [provider]
34
+ options = ort.SessionOptions()
35
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
36
+ session = ort.InferenceSession(str(args.model), options, providers=providers)
37
+ if session.get_inputs()[0].shape != [1, 3, 384, 288]:
38
+ raise ValueError('Model input does not match the browser contract')
39
+
40
+ def run(target, sample):
41
+ outputs = dict(zip([o.name for o in target.get_outputs()], target.run(None, {'input': sample})))
42
+ points, scores = outputs['keypoints'], outputs['scores']
43
+ if points.shape != (1, 133, 3) or scores.shape != (1, 133) or not np.isfinite(points).all() or not np.isfinite(scores).all():
44
+ raise RuntimeError('Invalid full-body output')
45
+
46
+ for i in range(5):
47
+ run(session, samples[i % 3])
48
+ times = []
49
+ begin = time.perf_counter()
50
+ for i in range(args.iterations):
51
+ start = time.perf_counter()
52
+ run(session, samples[i % 3])
53
+ times.append((time.perf_counter() - start) * 1000)
54
+ wall = (time.perf_counter() - begin) * 1000
55
+ del session
56
+ # Provider placement and node timing use a separate instrumented session.
57
+ provider_times, nodes = defaultdict(float), []
58
+ with tempfile.TemporaryDirectory(prefix='rtmw-native-profile-') as directory:
59
+ options.enable_profiling = True
60
+ options.profile_file_prefix = str(Path(directory) / 'profile')
61
+ diagnostic = ort.InferenceSession(str(args.model), options, providers=providers)
62
+ run(diagnostic, samples[0])
63
+ path = diagnostic.end_profiling()
64
+ events = json.loads(Path(path).read_text(encoding='utf-8'))
65
+ del diagnostic
66
+ for event in events:
67
+ selected = event.get('args', {}).get('provider')
68
+ if selected and event.get('cat') == 'Node' and event.get('name', '').endswith('_kernel_time'):
69
+ milliseconds = event.get('dur', 0) / 1000
70
+ provider_times[selected] += milliseconds
71
+ nodes.append({'name': event['name'], 'provider': selected, 'milliseconds': milliseconds})
72
+ if not any(name != 'CPUExecutionProvider' and total > 0 for name, total in provider_times.items()):
73
+ raise RuntimeError('No GPU provider nodes were observed in the native profile')
74
+ ordered = sorted(times)
75
+ with args.model.open('rb') as file:
76
+ digest = hashlib.sha256()
77
+ for chunk in iter(lambda: file.read(1024 * 1024), b''):
78
+ digest.update(chunk)
79
+ result = {'schema': 'rtmw3d-native-comparison/v1', 'onnxruntime': ort.__version__,
80
+ 'modelSha256': digest.hexdigest(), 'requestedProvider': provider, 'views': args.views,
81
+ 'metrics': {'p50Ms': ordered[int((len(ordered) - 1) * .5)], 'p95Ms': ordered[int((len(ordered) - 1) * .95)],
82
+ 'aggregateFPS': len(times) / wall * 1000, 'perInputFPS': len(times) / wall * 1000 / args.views,
83
+ 'actualInferences': len(times), 'wallMs': wall, 'sessionTimesMs': times},
84
+ 'separateProfile': {'providerMilliseconds': dict(provider_times), 'topNodes': sorted(nodes, key=lambda n: -n['milliseconds'])[:30]},
85
+ 'notes': ['Diagnostic path only; production remains browser-based', 'Same three normalized browser inputs; upload, inference and CPU output retrieval included',
86
+ 'CPU fallback nodes are disclosed in the separate profile', 'No video, tensor contents, landmark coordinates or device identity are included in this report']}
87
+ args.output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
88
+ print(json.dumps({'output': str(args.output), 'metrics': result['metrics'] | {'sessionTimesMs': None}}, indent=2))
89
+
90
+
91
+ if __name__ == '__main__':
92
+ main()