Skip to content

fix(metrics): normalize AMD core allocation ratio to percentage - #2527

Merged
hami-robot[bot] merged 2 commits into
Project-HAMi:masterfrom
yxxhero:fix/issue-2518-amd-core-allocated-ratio
Aug 10, 2026
Merged

fix(metrics): normalize AMD core allocation ratio to percentage#2527
hami-robot[bot] merged 2 commits into
Project-HAMi:masterfrom
yxxhero:fix/issue-2518-amd-core-allocated-ratio

Conversation

@yxxhero

@yxxhero yxxhero commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?
/kind bug

What this PR does / why we need it:

The container-level hami_vgpu_core_allocated_ratio metric emitted ContainerDevice.Usedcores directly. For AMD devices Usedcores stores physical compute-unit (CU) counts (cuCount = percentage × Totalcore / 100, see the AMD design doc), so the metric reported the raw CU count instead of a normalized percentage.

For example, a 50% core request on a 64-CU device is stored as Usedcores = 32, but the collector emitted:

hami_vgpu_core_allocated_ratio = 32

while the expected value is ceil(32 / 64 × 100) = 50.

Node-level normalization for AMD already landed via normalizeAMDCoreMetrics, but the container-level metric was missed — which is exactly what issue #2518 reports.

This PR:

  • Reuses the existing normalizeAMDCoreMetrics(deviceType, total, allocated) helper for the container-level hami_vgpu_core_allocated_ratio.
  • Extends the existing per-container device lookup (which previously only fetched an unused Totalmem) to also resolve the device's Totalcore and Type, then normalizes before emitting the metric.
  • Leaves legacy metrics untouched for backward compatibility (consistent with the node-level fix).
  • Adds a regression test (TestContainerCoreAllocatedRatioNormalizedForAMD) asserting hami_vgpu_core_allocated_ratio == 50 for an AMD container with 32 CUs used on a 64-CU device.

Which issue(s) this PR fixes:
Fixes #2518

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

Fix: hami_vgpu_core_allocated_ratio now reports a normalized core allocation percentage for AMD containers instead of the raw compute-unit count.

This PR was prepared with AI assistance and is disclosed per CONTRIBUTING.md.

Summary by CodeRabbit

  • Bug Fixes
    • Improved node and container memory metrics for more accurate capacity reporting.
    • Improved container device metrics by matching devices using their unique identifiers.
    • Corrected total memory, total core capacity, and device type reporting for containers.
    • Normalized AMD GPU core allocation metrics so reported percentages accurately reflect allocated capacity.
    • Preserved existing raw-value behavior for legacy core metrics.

@hami-robot hami-robot Bot added the kind/bug Something isn't working label Aug 9, 2026
@hami-robot
hami-robot Bot requested a review from archlitchi August 9, 2026 23:45
@hami-robot
hami-robot Bot requested a review from DSFans2014 August 9, 2026 23:45
@hami-robot hami-robot Bot added the size/L label Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Scheduler metrics now resolve devices by UUID and convert MiB values through a shared helper. AMD node and container core allocations use normalized percentages. Legacy metrics retain raw core allocations. Tests cover lookup, conversion, and normalization.

Changes

AMD core metric normalization

Layer / File(s) Summary
Device resolution and memory conversion
cmd/scheduler/metrics.go
The collector resolves device core capacity and type by UUID. Node, GPU overview, and legacy memory metrics use mibToBytes.
Container metric normalization
cmd/scheduler/metrics.go
Container metrics normalize AMD core allocations, reuse labels and converted memory values, and preserve raw legacy allocations.
Normalization regression coverage
cmd/scheduler/metrics_test.go
Tests cover MiB conversion, device lookup across nodes and device types, AMD allocation normalization to 50%, and the legacy raw value of 32.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: archlitchi, fouof

Poem

A rabbit counts the CUs with care,
Finds the device by UUID there.
Fifty percent now fills the chart,
Legacy numbers keep their part.
Hop, metrics align!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: normalizing AMD core allocation ratios in metrics.
Linked Issues check ✅ Passed The changes resolve AMD device capacity, normalize 32 of 64 CUs to 50%, preserve non-AMD and legacy behavior, and add regression tests for issue #2518.
Out of Scope Changes check ✅ Passed The MiB conversion helper, device lookup changes, metric updates, and tests directly support the stated metrics correction and related validation.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai
coderabbitai Bot requested a review from peachest August 9, 2026 23:46

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/scheduler/config/config.go`:
- Around line 281-294: The InitDevices flow must not retain partially
initialized global state when InitDevicesWithConfig fails. Update InitDevices
and/or InitDevicesWithConfig so device.DevicesMap is published only after all
backends succeed, or is cleared before returning an initialization error,
allowing subsequent calls to retry failed backends.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9422fe52-f8f3-41d0-b764-ea036486fe3e

📥 Commits

Reviewing files that changed from the base of the PR and between 3616313 and e14e10f.

📒 Files selected for processing (6)
  • cmd/scheduler/main.go
  • cmd/scheduler/metrics.go
  • cmd/scheduler/metrics_test.go
  • pkg/scheduler/config/config.go
  • pkg/scheduler/config/config_test.go
  • pkg/scheduler/nodes_test.go

Comment thread pkg/scheduler/config/config.go Outdated
@yxxhero
yxxhero force-pushed the fix/issue-2518-amd-core-allocated-ratio branch from e14e10f to 00c74e9 Compare August 9, 2026 23:53
@coderabbitai
coderabbitai Bot requested a review from FouoF August 9, 2026 23:54

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
cmd/scheduler/metrics_test.go (1)

208-212: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for node and legacy core metrics.

Line 211 selects only hami_vgpu_core_allocated_ratio. This test cannot detect a regression in hami_gpu_core_allocated_ratio or a change to the legacy raw core metric.

Set DeviceUsage.Usedcores to 32 and assert the node metric reports 50. Add a legacy-enabled assertion that the legacy container metric remains 32.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/scheduler/metrics_test.go` around lines 208 - 212, Extend the test around
CollectAndCompare to set DeviceUsage.Usedcores to 32 and validate
hami_gpu_core_allocated_ratio reports 50. Add a separate legacy-enabled
assertion confirming the legacy raw core metric remains 32, while preserving the
existing hami_vgpu_core_allocated_ratio check.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@cmd/scheduler/metrics_test.go`:
- Around line 208-212: Extend the test around CollectAndCompare to set
DeviceUsage.Usedcores to 32 and validate hami_gpu_core_allocated_ratio reports
50. Add a separate legacy-enabled assertion confirming the legacy raw core
metric remains 32, while preserving the existing hami_vgpu_core_allocated_ratio
check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 42521791-d98c-4073-8fac-e8b52a578d1e

📥 Commits

Reviewing files that changed from the base of the PR and between e14e10f and 00c74e9.

📒 Files selected for processing (2)
  • cmd/scheduler/metrics.go
  • cmd/scheduler/metrics_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/scheduler/metrics.go

yxxhero added a commit to yxxhero/HAMi that referenced this pull request Aug 9, 2026
Address review feedback on Project-HAMi#2527: extend the AMD regression test to also
assert hami_gpu_core_allocated_ratio == 50 at node level (setting
DeviceUsage.Usedcores = 32 on the 64-CU device) and add a legacy-enabled
assertion that vGPUCoreAllocated keeps the raw CU count (32) for backward
compatibility.

Signed-off-by: yxxhero <aiopsclub@163.com>
@yxxhero

yxxhero commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Addressed in 58b852c:

  • pkg/scheduler/config/config.go comment (on e14e10f): no longer applicable — that change came from an unrelated commit that was dropped when this PR was rebased onto master as a single commit. The PR now only touches cmd/scheduler/metrics.go and cmd/scheduler/metrics_test.go, so there's no InitDevices change here.
  • metrics_test.go nitpick (lines 208-212): done. The AMD regression test now also:
    • sets DeviceUsage.Usedcores = 32 on the 64-CU device and asserts the node-level hami_gpu_core_allocated_ratio == 50, and
    • adds a legacy-enabled assertion that vGPUCoreAllocated keeps the raw CU count (32) for backward compatibility,
    • while preserving the existing container-level hami_vgpu_core_allocated_ratio == 50 check.

go test --race, golangci-lint, goimports, and license/import-alias checks all pass.

@codecov

codecov Bot commented Aug 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.64706% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
cmd/scheduler/metrics.go 92.64% 0 Missing and 5 partials ⚠️
Flag Coverage Δ
unittests 64.29% <92.64%> (+0.08%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/scheduler/metrics.go 74.90% <92.64%> (+1.81%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…tage

The container-level hami_vgpu_core_allocated_ratio metric emitted
ContainerDevice.Usedcores directly. For AMD devices Usedcores stores
physical compute-unit (CU) counts (cuCount = percentage * Totalcore /
100), so the metric reported the raw CU count instead of a normalized
percentage: a 50% request on a 64-CU device was stored as 32 and emitted
as 32 rather than 50.

Node-level normalization already landed via normalizeAMDCoreMetrics, but
the container-level metric was missed (issue Project-HAMi#2518). Reuse that helper for
the container metric by resolving the matching node device's Totalcore and
Type, and leave legacy metrics untouched for backward compatibility.

Supporting readability refactors (no behavior change):
- Add findNodeDeviceUsage to replace the inline UUID lookup (previously a
  double loop with a break flag) and drop the dead Totalmem capture.
- Add mibToBytes and replace all eight float64(x)*float64(1024)*float64(1024)
  occurrences (node- and container-level, new and legacy).
- Hoist the repeated container label set into a single containerLabels
  slice and compute usedMemBytes once per container device.

Tests:
- TestAMDCoreAllocatedRatioNormalization asserts hami_vgpu_core_allocated_ratio
  == 50 and hami_gpu_core_allocated_ratio == 50 for an AMD container with 32
  CUs used on a 64-CU device, and that the legacy vGPUCoreAllocated stays 32.
- TestFindNodeDeviceUsage and TestMibToBytes cover the new helpers.

Fixes Project-HAMi#2518

Signed-off-by: yxxhero <aiopsclub@163.com>
@yxxhero
yxxhero force-pushed the fix/issue-2518-amd-core-allocated-ratio branch from 26cb85a to 33eedd3 Compare August 10, 2026 00:33
Collect had grown to ~250 lines mixing three independent concerns: node
device metrics, resource quota usage, and per-container metrics, each with
its own descriptor set. Decompose it into a thin orchestrator that takes a
single shared node-usage snapshot and delegates to:

- collectNodeMetrics: node-level limits/allocations, sharing, MIG, overview
- collectQuotaMetrics: per-namespace resource quota usage
- collectContainerMetrics: per-container vGPU metrics (incl. AMD normalization)

Each helper owns only the descriptors it emits, replacing the single large
shared descriptor block.

This is a pure structural relocation with no behavior change: every metric
name, help text, label set, and emitted value is byte-identical (verified
by diffing the sorted set of NewDesc/send* calls before and after, plus the
existing pedantic-registry and CollectAndCompare tests).

Signed-off-by: yxxhero <aiopsclub@163.com>
@FouoF

FouoF commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

/lgtm

@hami-robot hami-robot Bot added the lgtm label Aug 10, 2026
@hami-robot

hami-robot Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: FouoF, yxxhero

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AMD container core allocation ratio reports physical CU count instead of percentage

2 participants