MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / linspace

Function linspace

imperative/python/megengine/xla/rules/tensor.py:246–293  ·  view source on GitHub ↗
(
    start: Union[int, float, HLOTensor],
    stop: Union[int, float, HLOTensor],
    num: Union[int, HLOTensor],
    dtype=np.float32,
    oshape=None,
)

Source from the content-addressed store, hash-verified

244
245
246def linspace(
247 start: Union[int, float, HLOTensor],
248 stop: Union[int, float, HLOTensor],
249 num: Union[int, HLOTensor],
250 dtype=np.float32,
251 oshape=None,
252):
253 if isinstance(num, HLOTensor):
254 assert (
255 oshape is not None
256 ), "if num is a HLOTensor, please specify the output shape with oshape"
257
258 if isinstance(num, int) and oshape is not None:
259 assert _shape_equal(
260 oshape, (num,)
261 ), f"shape error: shape {oshape} .vs num {num}"
262
263 oshape = (num,) if oshape is None else oshape
264
265 if any([isinstance(x, HLOTensor) for x in [start, stop, num]]):
266 start, stop, num = [
267 x if isinstance(x, HLOTensor) else HLOTensor(float(x))
268 for x in [start, stop, num]
269 ]
270 start, stop, num = [
271 x if x.dtype == np.float32 else x.astype(np.float32)
272 for x in [start, stop, num]
273 ]
274 # we want to implement: scale = where(num==1, 0.0, (stop-start)/(num-1.0))
275 # to avoid divided by zero, but xla where is implemented by mul and add, the
276 # result is still NAN, so we add a huge number to num to simulate.
277 # we use 1e32 rather than np.inf because np.inf * zero will also return NAN
278 num_refactor = where(num == 1.0, 1e32, num)
279 scale = (stop - start) / (num_refactor - 1.0)
280 scale = where(num == 1.0, 0.0, scale)
281 offset = start
282 else:
283 assert all([isinstance(x, (int, float)) for x in [start, stop, num]])
284 if num == 1:
285 scale = 0
286 else:
287 scale = (stop - start) / (num - 1.0)
288 offset = float(start)
289
290 fsrc = iota(np.float32, oshape, -1)
291 fout = fsrc * scale + offset
292
293 return fout if dtype == np.float32 else fout.astype(dtype)
294
295
296def arange(

Callers 2

arangeFunction · 0.70
linspace_lowerFunction · 0.70

Calls 5

_shape_equalFunction · 0.85
HLOTensorClass · 0.85
whereFunction · 0.70
iotaFunction · 0.70
astypeMethod · 0.45

Tested by

no test coverage detected