Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions projects/hipblaslt/tensilelite/Tensile/Contractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,14 +534,25 @@ def CompoundPredicates(cls, state, problemType):

rv += [cls('SynchronizerSizeCheck', index=0, value=valuepredicates)]

if state["InternalSupportParams"]["KernArgsVersion"] >= 1 and \
not (('StreamK' in state) and (state['StreamK'] > 0)):
isStreamK = ('StreamK' in state) and (state['StreamK'] > 0)
if state["InternalSupportParams"]["KernArgsVersion"] >= 1 and not isStreamK:
valuepredicates = []
valuepredicates.append(state["MacroTile0"])
valuepredicates.append(state["MacroTile1"])
valuepredicates.append(state["GlobalSplitU"])
rv += [cls('WorkgroupNumberCheck', index=0, value=valuepredicates)]

if isStreamK:
# Stream-K's normal grid is CU-scaled, not tile-scaled, so it is
# exempt from WorkgroupNumberCheck above. But several launch-time
# fallbacks (workspace too small for the ideal partial-tile
# reduction, the tree-fixup 24-bit bounds guard, a fixed-grid
# debug override, ...) hand Stream-K a one-workgroup-per-tile grid
# instead, same shape as the tile-scaled grid WorkgroupNumberCheck
# already bounds. Bound that worst case too.
rv += [cls('StreamKWorkgroupNumberCheck',
value=[state["MacroTile0"], state["MacroTile1"]])]

if not problemType.aType.isInt8x4():
# calculate the minimum supported free dimension size
TLUA = state['ProblemType']['TLUA']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,48 @@ def solution_state():
return dict(sol._state)


# Real gfx950 Stream-K (static, StreamK: 3) solution, already vendored for the
# BenchmarkProblems solution-pool tests (test_benchmarkProblems_solution_pool.py,
# test_LibraryIO.py). Reused here, rather than patching a synthetic 'StreamK'
# key onto the gfx942 fixture above, so the isStreamK branch in
# CompoundPredicates() (Contractions.py) is exercised against a solution
# state a real Stream-K kernel actually has, not a hand-edited one. Kept as
# its own separate fixture chain (rather than sharing helpers with raw/
# problem_type/solution_state above) so this addition cannot change the
# behavior of the existing fixtures/tests.
_STREAMK_FIXTURE = (
Path(__file__).parent.parent.parent / "test_data" / "solution_pool_gfx950.yaml"
)


@pytest.fixture(scope="module")
def raw_streamk():
doc = _STREAMK_FIXTURE.read_text()
return yaml.load(doc, Loader=L.StrictTypeLoader) # nosec B506


@pytest.fixture
def problem_type_streamk(raw_streamk):
return C.ProblemType.FromOriginalState(raw_streamk[4])


@pytest.fixture(scope="module")
def solution_state_streamk():
from Tensile.Common.Architectures import SUPPORTED_ISA
from Tensile.Common.Capabilities import makeIsaInfoMap
from Tensile.Toolchain.Assembly import makeAssemblyToolchain
from Tensile.Toolchain.Validators import validateToolchain, ToolchainDefaults

cxx = validateToolchain("amdclang++")
iim = makeIsaInfoMap(SUPPORTED_ISA, cxx)
bundler = validateToolchain(ToolchainDefaults.OFFLOAD_BUNDLER)
asm = makeAssemblyToolchain(cxx, bundler, "default").assembler
sol = L.parseLibraryLogicFile(
str(_STREAMK_FIXTURE), asm, False, False, False, iim, False
).solutions[0]
return dict(sol._state)


# --- index value classes ----------------------------------------------------

def test_index_classes(snapshot):
Expand Down Expand Up @@ -99,3 +141,18 @@ def test_internal_args_support(solution_state):
def test_problem_predicate_compound(problem_type, solution_state, snapshot):
preds = C.ProblemPredicate.CompoundPredicates(solution_state, problem_type)
assert {"count": len(preds), "tags": sorted({p.tag for p in preds})} == snapshot


def test_problem_predicate_compound_streamk(problem_type_streamk, solution_state_streamk):
# test_problem_predicate_compound above never exercises
# CompoundPredicates()'s isStreamK branch (Contractions.py): the vendored
# gfx942 fixture's solution has no StreamK field. This drives the same
# call from a real Stream-K solution's derived state instead, which must
# skip the ordinary WorkgroupNumberCheck and attach
# StreamKWorkgroupNumberCheck in its place.
tags = {
p.tag
for p in C.ProblemPredicate.CompoundPredicates(solution_state_streamk, problem_type_streamk)
}
assert "StreamKWorkgroupNumberCheck" in tags
assert "WorkgroupNumberCheck" not in tags
Original file line number Diff line number Diff line change
Expand Up @@ -548,3 +548,43 @@ the selectors after an intentional generation-input change.
the exact emitter-status multiset for its bounded sample. Remove throwaway
warm-up emits because canonicalization already removes the known scheduler-state
difference.

## D33 — `Contractions.py`: first arm of the deferred predicate/state matrix (isStreamK)

**Context:** ADR 0007 (D10) deferred the `ProblemPredicate.CompoundPredicates`
arms that only fire for other-problem-configurations — including the
`isStreamK` branch, which swaps the ordinary `WorkgroupNumberCheck` for
`StreamKWorkgroupNumberCheck` — for a future "Contractions matrix" slice, and
explicitly rejected hand-synthesizing a derived-solution state for that slice
("fragile, since they must match the full post-derivation key set exactly").
While adding `StreamKWorkgroupNumberCheck` for ROCM-31290, this branch
initially got exactly that rejected treatment: a synthetic
`dict(solution_state, StreamK=1)` patched onto the vendored gfx942-HSS
fixture's derived state.

**Decision:** Replaced the synthetic patch with a second fixture chain
(`raw_streamk` / `problem_type_streamk` / `solution_state_streamk`) parsed via
the same `parseLibraryLogicFile` path, pointed at
`Tensile/Tests/unit/test_data/solution_pool_gfx950.yaml` — a real gfx950
static Stream-K (`StreamK: 3`) solution already vendored for the
BenchmarkProblems solution-pool tests (`test_LibraryIO.py`,
`test_benchmarkProblems_solution_pool.py`). `test_problem_predicate_compound_streamk`
now asserts the `isStreamK` swap against a real derived state instead of a
hand-edited one. Kept as a fully separate fixture chain from
`raw`/`problem_type`/`solution_state` (no shared helpers) so the addition
cannot change the existing fixtures' behavior.

**Why:** This reuses an already-vendored fixture rather than vendoring a new
logic YAML or hand-synthesizing state, so it avoids both alternatives ADR
0007 rejected, while covering the first of the deferred arms. It does not
close ADR 0007 — sparse, activation, bias, batched, and dtype arms remain
deferred — so ADR 0007 stays `Accepted` as-is.

**Alternatives rejected:**
- Keep the synthetic `dict(solution_state, StreamK=1)` patch — rejected per
ADR 0007's own reasoning: a hand-edited state isn't guaranteed to match
what `Solution` construction actually derives for a real Stream-K solution,
so it could pass while a real one fails (or vice versa).
- Vendor a new, purpose-built gfx950 StreamK logic fixture for this test —
rejected as unnecessary; a suitable one is already vendored and exercised
elsewhere in the suite.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
#include <array>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <sstream>
#include <vector>
Expand Down Expand Up @@ -1636,6 +1637,152 @@ namespace TensileLite
}
};

struct StreamKWorkgroupNumberCheck
: public Predicate_CRTP<StreamKWorkgroupNumberCheck, ContractionProblemGemm>
{
enum
{
HasIndex = false,
HasValue = true
};
std::array<int, 2> value; // [MacroTile0, MacroTile1]

StreamKWorkgroupNumberCheck() = default;
StreamKWorkgroupNumberCheck(std::array<int, 2> value)
: value(value)
{
}

static std::string Type()
{
return "StreamKWorkgroupNumberCheck";
}

// WorkgroupNumberCheck above skips Stream-K solutions because
// Stream-K's normal grid is CU-scaled, not tile-scaled. But
// several launch-time fallbacks (workspace too small for the
// ideal partial-tile reduction, the tree-fixup 24-bit bounds
// guard, a fixed-grid debug override, ...) hand Stream-K a
// one-workgroup-per-tile grid instead, same as the plain
// tile-scaled grid WorkgroupNumberCheck already bounds. Any of
// those fallbacks can fire at launch time depending on
// workspace and hardware, so this is checked unconditionally
// for every Stream-K solution rather than only when a
// fallback is predicted: if the tile grid itself is unsafe,
// dispatch cannot rely on always landing on the CU-scaled
// path.

// Integer ceiling division, exact for every input; a float
// ceil() here would lose precision once a dimension exceeds
// 2^24 and could undercount tiles right at the boundary this
// predicate exists to guard.
static size_t ceilDiv(size_t numerator, size_t denominator)
{
return (numerator + denominator - 1) / denominator;
}

// Mirrors ContractionProblemGemm::getNumTiles(sizeMapping, 1), the
// count solve() builds the fallback grid from: the product of every
// free index on each side divided by its macro tile, times the
// product of every batch index.
//
// Every index is accumulated rather than taking index 0, the way
// WorkgroupNumberCheck and the LeadingFree*SizesGreaterOrEqual
// predicates do. Those carry an assert(batchIndices().size() <= 1)
// that compiles out of a release build. Taking index 0 alone
// under-counts a multi-free-index or multi-batch contraction, and
// under-counting admits a grid that then wraps, which is precisely
// the failure this predicate exists to prevent.
//
// Computed here rather than delegated because a predicate is handed
// MacroTile0/MacroTile1 as its value and never sees the solution's
// sizeMapping, so it cannot consult packBatchDims. That is the one
// remaining divergence from getNumTiles, and it is not uniformly
// safe:
//
// packBatchDims 0 : batch lands in numWG.z; identical to this.
// packBatchDims 1 : batch folds into M before the divide, 2 into
// N. Folding before the divide can only lose to
// multiplying after, so this over-counts and
// only rejects more.
// packBatchDims 3 : batch folds into M *and* N, so getNumTiles
// scales by batch squared while this scales by
// batch. This under-counts. One batch of 2 at a
// 16x16 tile gives getNumTiles 1024 against 512
// here.
//
// Only mode 3 is unsafe, and it does not occur: packBatchDims is 0
// in all 77,421 solutions of the shipped gfx950 library. If a tuned
// library ever ships mode 3, this predicate needs the packing mode
// carried in its serialized value to stay correct. Until then the
// launch guard in SolutionAdapter::launchKernel is the backstop; it
// bounds the grid it is actually handed, so an under-count here
// surfaces as hipErrorInvalidValue rather than silent truncation.
static size_t tiles(ContractionProblemGemm const& problem,
std::array<int, 2> const& value)
{
size_t freeA = 1;
for(size_t i = 0; i < problem.freeIndicesA().size(); i++)
freeA *= problem.freeSizeA(i);

size_t freeB = 1;
for(size_t i = 0; i < problem.freeIndicesB().size(); i++)
freeB *= problem.freeSizeB(i);

size_t batch = 1;
for(size_t i = 0; i < problem.batchIndices().size(); i++)
batch *= problem.batchSize(i);

return ceilDiv(freeA, value[0]) * ceilDiv(freeB, value[1]) * batch;
}

// The launch narrows the 64-bit work-item count
// (workGroupSize * numWorkGroups, both size_t) to the
// `unsigned int` globalWorkSize parameters of
// hipExtModuleLaunchKernel, so a tile-scaled Stream-K grid is
// only safe while that product still fits in 32 bits.
// Measured on gfx950 at 256 threads: 2^24 + 16 workgroups
// wraps to a 16-workgroup grid and leaves the other
// 16,777,216 workgroups' worth of D unwritten with no error
// reported, and 2^24 workgroups lands on exactly 2^32, which
// narrows to 0 and HIP rejects outright.
//
// NumThreads is not carried in this predicate's value, so the
// bound assumes the 256-thread configuration that dominates
// the shipped Stream-K solutions. That is exact at 256
// threads, conservative at 64 and 128 (whose real limits are
// 2^26 and 2^25), and still too loose for the one 512-thread
// family, MacroTile 448x128, which wraps at 2^23 but needs
// roughly 896 GiB of D to get there. Deliberately *not*
// MAX_WORKGROUP_NUMBER: that constant happens to have the
// same magnitude but guards an unrelated fp32 conversion.
static constexpr size_t MAX_STREAMK_TILE_COUNT
= std::numeric_limits<uint32_t>::max() / 256;

virtual bool operator()(ContractionProblemGemm const& problem) const override
{
return tiles(problem, value) <= MAX_STREAMK_TILE_COUNT;
}

virtual std::string toString() const override
{
return concatenate(this->type(), "(MT0:", value[0], ",MT1:", value[1], ")");
}

virtual bool debugEval(ContractionProblemGemm const& problem,
std::ostream& stream) const override
{
return debugEvalCmp(problem,
stream,
"sk_tiles",
tiles(problem, value),
"<=",
"max",
MAX_STREAMK_TILE_COUNT);
}
};


struct PersistentKernelCheck
: public Predicate_CRTP<PersistentKernelCheck, ContractionProblemGemm>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ namespace TensileLite
Predicates::Contraction::BufferLoadOffsetLimitCheck_Beta>(),
Base::template Pair<Predicates::Contraction::BufferStoreOffsetLimitCheck>(),
Base::template Pair<Predicates::Contraction::WorkgroupNumberCheck>(),
Base::template Pair<Predicates::Contraction::StreamKWorkgroupNumberCheck>(),
Base::template Pair<Predicates::Contraction::PersistentKernelCheck>(),
Base::template Pair<Predicates::Contraction::GlobalSplitUCheckMinK>(),
Base::template Pair<Predicates::Contraction::CDStridesEqual>(),
Expand Down Expand Up @@ -364,6 +365,12 @@ namespace TensileLite
{
};

template <typename IO>
struct MappingTraits<Predicates::Contraction::StreamKWorkgroupNumberCheck, IO>
: public AutoMappingTraits<Predicates::Contraction::StreamKWorkgroupNumberCheck, IO>
{
};

template <typename IO>
struct MappingTraits<Predicates::Contraction::PersistentKernelCheck, IO>
: public AutoMappingTraits<Predicates::Contraction::PersistentKernelCheck, IO>
Expand Down
Loading
Loading