harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0340harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0340Task: Harden and scale a minimal MindSpore-like API under /app/mindspore with concurrency, robust edge-case handling, and a stricter API design.
What you must implement (self-contained, actionable, and wired to the test expectations)
1) Package layout (recommended)
- Create a package at /app/mindspore with:
- __init__.py
- context.py
- tensor.py (optional internal module, but the public API must be accessible via mindspore.Tensor)
- nn/
- __init__.py
- SoftmaxCrossEntropyWithLogits implemented as a class in this module
- The public API must be importable as:
- from mindspore import Tensor
- import mindspore.context as context
- import mindspore.nn as nn
- The test will rely on the above structure; no external dependencies beyond NumPy.
2) Tensor type (mindspore.Tensor)
- Implement a simple Tensor wrapper that the tests can use via:
- from mindspore import Tensor
- API guarantees:
- class Tensor:
- __init__(self, data): store a NumPy array; if data is not a NumPy array, convert it to one (e.g., list to np.array)
- def asnumpy(self) -> numpy.ndarray: return the underlying NumPy array (a real NumPy array, not a view-shape wrapper)
- Behavior expected by tests:
- The test constructs logits and labels as NumPy arrays wrapped by Tensor:
logits = Tensor(np.array([...]).astype(np.float32))
labels = Tensor(np.array([...]).astype(np.float32))
- A Tensor is also passed through operations inside mindspore.nn.SoftmaxCrossEntropyWithLogits, and the final result of a forward pass is a Tensor whose asnumpy() yields a 1D NumPy array with length equal to the batch size (3 in the test).
- Implementation note: ensure compatibility with both raw NumPy arrays and Tensor inputs in the loss implementation.
3) Context module
- Implement a minimal context API in mindspore/context.py:
- Expose a constant:
- GRAPH_MODE (value should be an int, e.g., 0)
- Expose a function:
- def set_context(mode, device_target=None): store the provided mode and device_target in some internal state (no real hardware interaction needed)
- Tests call:
context.set_context(mode=context.GRAPH_MODE, device_target='CPU')
So you must allow passing mode as the GRAPH_MODE constant and ignore other parameters beyond storing them.
- Internal state should be accessible for debugging and future extension but must not crash on repeated calls.
4) Neural network namespace (nn)
- Implement a minimal neural network base and the required loss component in mindspore/nn/__init__.py:
- Base class:
- class Cell:
- def __init__(self): pass
- def __call__(self, *args, **kwargs): return self.construct(*args, **kwargs)
- def construct(self, *args, **kwargs): raise NotImplementedError
- SoftmaxCrossEntropyWithLogits loss:
- class SoftmaxCrossEntropyWithLogits(Cell):
- def __init__(self, sparse=False):
- Store the sparse flag (tests use sparse=False)
- The class should be callable via the inherited __call__, which will invoke construct.
- def construct(self, logits, labels) -> Tensor:
- Accept logits and labels as either mindspore.Tensor or raw NumPy arrays
- If inputs are Tensor, extract their underlying NumPy arrays
- Compute per-sample softmax cross-entropy with logits and one-hot labels (sparse=False)
- Supported shapes: logits shape (N, C) and labels shape (N, C) when sparse=False
- If sparse=True, labels are class indices shape (N,)
- Implementation requirements:
- Use numerically stable softmax
- Compute per-sample cross-entropy, returning a 1D NumPy array of length N
- The result must be wrapped in a mindspore Tensor before returning
- The test expects a Tensor whose asnumpy() yields a 1D array of length N
- The final numeric values should align with standard cross-entropy on the provided inputs
- The SoftmaxCrossEntropyWithLogits must be robust to:
- Inputs provided as either Tensor or NumPy arrays
- Empty inputs (N=0 or C=0) returning an empty 1D tensor of shape (0,)
- Mismatched shapes raising a clear, meaningful error
- Non-numeric inputs raising an informative error
5) Core behavior and test alignment
- The implemented SoftmaxCrossEntropyWithLogits should produce per-sample losses that, for the given test inputs, yield approximately:
[0.00024673, 0.00024673, 0.00024673]
- The resulting output must be accessible via output.asnumpy() returning a NumPy array of shape (3,)
- The test uses the following interactions:
- Net = subclass of Cell that initializes self.loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
- Net.__call__(logits, labels) triggers self.loss(logits, labels) via construct
- The test enables GRAPH_MODE context and CPU target, then calls Net with two MindSpore Tensors
- The final result’s asnumpy() is compared against the expected values within a tight tolerance
- Your implementation must preserve deterministic behavior across runs.
6) Performance, edge-cases, and design constraints (harder)
- Performance:
- Strive for O(N*C) time and O(N*C) memory in the vectorized path
- For large inputs, implement a concurrent path that computes per-row cross-entropy contributions using a thread pool (ThreadPoolExecutor) to demonstrate concurrency, while ensuring the final result remains numerically identical to the vectorized path
- Do not rely on Python-level loops for the main computation on typical large inputs
- Edge cases:
- Empty inputs: logits.shape == (0, C) and/or labels.shape == (0, C) or (0,)
- Mismatched shapes: raise ValueError with a clear message
- Non-numeric inputs: raise TypeError with a helpful message
- Very large C or N values: ensure numerical stability and minimal memory overhead
- Design patterns:
- Use a small internal helper to encapsulate the per-row computation and expose it via a thread-safe interface
- The Cell class should act as a clean base with __call__ forwarding to construct
- Keep public API surface minimal and well-documented to facilitate extension
- Implementation discipline:
- Pure-Python with NumPy only (no external dependencies)
- Deterministic and reproducible results
- Comprehensive docstrings and comments explaining concurrency strategy, edge-case handling, and shape requirements
7) Deliverable
- A Python package at /app/mindspore (with modules __init__.py, context.py, and nn/__init__.py that satisfy imports and test expectations)
- A Tensor wrapper accessible via from mindspore import Tensor
- A minimal context module providing GRAPH_MODE and set_context with internal state
- A functional SoftmaxCrossEntropyWithLogits that supports sparse=False and sparse=True, uses a stable, efficient, and concurrent approach, returns a Tensor, and handles edge cases gracefully
- All computations must be deterministic and align with the test’s expected numeric results
Notes
- The solution must be self-contained and runnable within the test harness environment without additional installation steps.
- The final code must live under /app/ and be importable exactly as mindspore.* as described.