跳至内容

创建

创建(基础)¤

staticmethod ¤

empty(
    *shape,
    device: str | tuple[str, ...] | None = None,
    dtype: DTypeLike | None = None,
    **kwargs
) -> Tensor

创建一个具有给定形状的空张量。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

t = Tensor.empty(2, 3)
print(t.shape)
(2, 3)
Source code in tinygrad/tensor.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
@staticmethod
def empty(*shape, device:str|tuple[str, ...]|None=None, dtype:DTypeLike|None=None, **kwargs) -> Tensor:
  """
  Creates an empty tensor with the given shape.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  t = Tensor.empty(2, 3)
  print(t.shape)
  ```
  """
  dtype, shape = to_dtype(dtype) if dtype is not None else dtypes.default_float, argfix(*shape)
  if not isinstance(size:=prod([x.vmax if isinstance(x, UOp) else x for x in shape]), int): raise ValueError(f"size must be int {size}")
  if isinstance(device, tuple):
    return Tensor(UOp.multi(*[UOp.new_buffer(Device.canonicalize(d), size, dtype).reshape(shape) for d in device], axis=None),
                  device, dtype, **kwargs)
  return Tensor(UOp.new_buffer(Device.canonicalize(device), size, dtype), device, dtype, **kwargs).reshape(shape)

zeros staticmethod ¤

zeros(*shape, **kwargs) -> Tensor

创建一个具有给定形状的张量,并用零填充。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.zeros(2, 3).numpy())
[[0. 0. 0.]
 [0. 0. 0.]]
print(Tensor.zeros(2, 3, dtype=dtypes.int32).numpy())
[[0 0 0]
 [0 0 0]]

Source code in tinygrad/tensor.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
@staticmethod
def zeros(*shape, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with zeros.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.zeros(2, 3).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.zeros(2, 3, dtype=dtypes.int32).numpy())
  ```
  """
  return Tensor.full(argfix(*shape), 0.0, **kwargs)

ones staticmethod ¤

ones(*shape, **kwargs) -> Tensor

创建一个具有给定形状的张量,并用1填充。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.ones(2, 3).numpy())
[[1. 1. 1.]
 [1. 1. 1.]]
print(Tensor.ones(2, 3, dtype=dtypes.int32).numpy())
[[1 1 1]
 [1 1 1]]

Source code in tinygrad/tensor.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
@staticmethod
def ones(*shape, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with ones.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.ones(2, 3).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.ones(2, 3, dtype=dtypes.int32).numpy())
  ```
  """
  return Tensor.full(argfix(*shape), 1.0, **kwargs)

完整 staticmethod ¤

full(
    shape: tuple[sint, ...], fill_value: ConstType, **kwargs
) -> Tensor

创建一个具有给定形状的张量,并用给定值填充。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.full((2, 3), 42).numpy())
[[42 42 42]
 [42 42 42]]
print(Tensor.full((2, 3), False).numpy())
[[False False False]
 [False False False]]

Source code in tinygrad/tensor.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@staticmethod
def full(shape:tuple[sint, ...], fill_value:ConstType, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with the given value.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.full((2, 3), 42).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.full((2, 3), False).numpy())
  ```
  """
  return Tensor(fill_value, **kwargs).reshape((1, )*len(new_shape := argfix(shape))).expand(new_shape)

arange staticmethod ¤

arange(start, stop=None, step=1, **kwargs) -> Tensor

返回一个大小为ceil((stop - start) / step)的一维张量,其值来自[start, stop)区间,值之间的间隔由step给出。

如果未指定stop,则使用给定的step[0, start)生成值。

如果指定了stop,则数值将从[start, stop)区间内按给定的step步长生成。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.arange(5).numpy())
[0 1 2 3 4]
print(Tensor.arange(5, 10).numpy())
[5 6 7 8 9]
print(Tensor.arange(5, 10, 2).numpy())
[5 7 9]
print(Tensor.arange(5.5, 10, 2).numpy())
[5.5 7.5 9.5]

Source code in tinygrad/tensor.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
@staticmethod
def arange(start, stop=None, step=1, **kwargs) -> Tensor:
  """
  Returns a 1-D tensor of size `ceil((stop - start) / step)` with values from `[start, stop)`, with spacing between values given by `step`.

  If `stop` is not specified, values are generated from `[0, start)` with the given `step`.

  If `stop` is specified, values are generated from `[start, stop)` with the given `step`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.arange(5).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.arange(5, 10).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.arange(5, 10, 2).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.arange(5.5, 10, 2).numpy())
  ```
  """
  if stop is None: stop, start = start, 0
  dtype = kwargs.pop("dtype", dtypes.default_float if any(isinstance(x, float) for x in (start, stop, step)) else dtypes.default_int)
  # NOTE: this matches numpy, torch raises RuntimeError if stop-start and step have different signs
  if (output_len:=ceildiv(stop-start, step)) <= 0: return Tensor([], dtype=dtype, **kwargs)
  return (Tensor.full((output_len,), step, dtype=dtype, **kwargs)._cumalu(0, Ops.ADD) + (start - step)).cast(dtype)

linspace staticmethod ¤

linspace(
    start: int | float,
    stop: int | float,
    steps: int,
    **kwargs
) -> Tensor

返回一个1维张量,包含从startstop(包含两端)均匀分布的steps个值。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.linspace(0, 10, 5).numpy())
[ 0.   2.5  5.   7.5 10. ]
print(Tensor.linspace(-1, 1, 5).numpy())
[-1.  -0.5  0.   0.5  1. ]

Source code in tinygrad/tensor.py
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
@staticmethod
def linspace(start:int|float, stop:int|float, steps:int, **kwargs) -> Tensor:
  """
  Returns a 1-D tensor of `steps` evenly spaced values from `start` to `stop`, inclusive.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.linspace(0, 10, 5).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.linspace(-1, 1, 5).numpy())
  ```
  """
  if steps < 0: raise ValueError("number of steps must be non-negative")
  if (dtype := to_dtype(kwargs.pop("dtype", dtypes.default_float))) == dtypes.bool: raise ValueError("linspace with bool dtype is not supported")
  if steps == 1: return Tensor([start], dtype=dtype, **kwargs)
  return (start + Tensor.arange(steps, **kwargs) * ((stop - start) / (steps - 1))).cast(dtype)

eye staticmethod ¤

eye(n: int, m: int | None = None, **kwargs) -> Tensor

返回一个具有n行和m列的2-D张量,对角线上的元素为1,其余位置为0。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

print(Tensor.eye(3).numpy())
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
print(Tensor.eye(2, 4).numpy())
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]]
Source code in tinygrad/tensor.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
@staticmethod
def eye(n:int, m:int|None=None, **kwargs) -> Tensor:
  """
  Returns a 2-D tensor with `n` rows and `m` columns, with ones on the diagonal and zeros elsewhere.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.eye(3).numpy())
  ```

  ```python exec="true" source="above" session="tensor" result="python"
  print(Tensor.eye(2, 4).numpy())
  ```
  """
  if n < 0 or (m is not None and m < 0): raise ValueError(f"cannot have negative {n=}, {m=}")
  x = Tensor.ones((n,1),**kwargs).pad((None,(0,n))).flatten().shrink(((0,n*n),)).reshape(n,n)
  return x if m is None else x.pad((None, (0, m-n))) if m > n else x.shrink((None, (0, m)))

full_like ¤

full_like(fill_value: ConstType, **kwargs) -> Tensor

创建一个与self形状相同的张量,并用给定值填充。 如果未指定dtype,则使用self的数据类型。

你可以传入device关键字参数来控制张量的设备。 此外,所有其他关键字参数都会被传递给张量的构造函数。

t = Tensor.ones(2, 3)
print(Tensor.full_like(t, 42).numpy())
[[42. 42. 42.]
 [42. 42. 42.]]
Source code in tinygrad/tensor.py
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def full_like(self, fill_value:ConstType, **kwargs) -> Tensor:
  """
  Creates a tensor with the same shape as `self`, filled with the given value.
  If `dtype` is not specified, the dtype of `self` is used.

  You can pass in the `device` keyword argument to control device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  t = Tensor.ones(2, 3)
  print(Tensor.full_like(t, 42).numpy())
  ```
  """
  return Tensor.full(self.shape, fill_value, dtype=kwargs.pop("dtype", self.dtype), device=kwargs.pop("device", self.device), **kwargs)

zeros_like ¤

zeros_like(**kwargs) -> Tensor

创建一个与self形状相同的张量,并用零填充。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

t = Tensor.ones(2, 3)
print(Tensor.zeros_like(t).numpy())
[[0. 0. 0.]
 [0. 0. 0.]]
Source code in tinygrad/tensor.py
669
670
671
672
673
674
675
676
677
678
679
680
681
def zeros_like(self, **kwargs) -> Tensor:
  """
  Creates a tensor with the same shape as `self`, filled with zeros.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  t = Tensor.ones(2, 3)
  print(Tensor.zeros_like(t).numpy())
  ```
  """
  return self.full_like(0, **kwargs)

ones_like ¤

ones_like(**kwargs) -> Tensor

创建一个与self形状相同的张量,并用1填充。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

t = Tensor.zeros(2, 3)
print(Tensor.ones_like(t).numpy())
[[1. 1. 1.]
 [1. 1. 1.]]
Source code in tinygrad/tensor.py
683
684
685
686
687
688
689
690
691
692
693
694
695
def ones_like(self, **kwargs) -> Tensor:
  """
  Creates a tensor with the same shape as `self`, filled with ones.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  t = Tensor.zeros(2, 3)
  print(Tensor.ones_like(t).numpy())
  ```
  """
  return self.full_like(1, **kwargs)

创建 (外部)¤

from_blob staticmethod ¤

from_blob(
    ptr: int, shape: tuple[int, ...], **kwargs
) -> Tensor

将指针作为Tensor暴露出来,但不获取原始数据的所有权。 该指针必须在创建的Tensor的整个生命周期内保持有效。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Source code in tinygrad/tensor.py
428
429
430
431
432
433
434
435
436
437
438
439
@staticmethod
def from_blob(ptr:int, shape:tuple[int, ...], **kwargs) -> Tensor:
  """
  Exposes the pointer as a Tensor without taking ownership of the original data.
  The pointer must remain valid for the entire lifetime of the created Tensor.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.
  """
  r = Tensor.empty(*shape, **kwargs)
  r.lazydata.buffer.allocate(external_ptr=ptr)
  return r

from_url staticmethod ¤

from_url(
    url: str, gunzip: bool = False, **kwargs
) -> Tensor

从URL创建一个Tensor。

这是访问互联网资源的推荐方式。 目前它会返回一个DISK Tensor,但未来可能会返回一个HTTP Tensor。 该功能很快将实现惰性加载(在可能的情况下),并且在非DEBUG模式下不会显示进度。

THe gunzip 标志将对资源进行gzip解压并返回解压后的Tensor。

Source code in tinygrad/tensor.py
441
442
443
444
445
446
447
448
449
450
451
452
@staticmethod
def from_url(url:str, gunzip:bool=False, **kwargs) -> Tensor:
  """
  Create a Tensor from a URL.

  This is the preferred way to access Internet resources.
  It currently returns a DISK Tensor, but in the future it may return an HTTP Tensor.
  This also will soon become lazy (when possible) and not print progress without DEBUG.

  THe `gunzip` flag will gzip extract the resource and return an extracted Tensor.
  """
  return Tensor(fetch(url, gunzip=gunzip), **kwargs)

创建(随机)¤

manual_seed staticmethod ¤

manual_seed(seed=0) -> None

设置随机操作的种子值。

Tensor.manual_seed(42)
print(Tensor.rand(5).numpy())
print(Tensor.rand(5).numpy())
[0.997  0.5899 0.2225 0.7551 0.9057]
[0.6162 0.6213 0.9791 0.7851 0.4178]
Tensor.manual_seed(42)  # 重置为相同的种子
print(Tensor.rand(5).numpy())
print(Tensor.rand(5).numpy())
[0.997  0.5899 0.2225 0.7551 0.9057]
[0.6162 0.6213 0.9791 0.7851 0.4178]

Source code in tinygrad/tensor.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
@staticmethod
def manual_seed(seed=0) -> None:
  """
  Sets the seed for random operations.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.rand(5).numpy())
  print(Tensor.rand(5).numpy())
  ```
  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)  # reset to the same seed
  print(Tensor.rand(5).numpy())
  print(Tensor.rand(5).numpy())
  ```
  """
  Tensor._seed, Tensor._device_seeds, Tensor._device_rng_counters = seed, {}, {}

随机数 staticmethod ¤

rand(
    *shape,
    device: str | None = None,
    dtype: DTypeLike | None = None,
    contiguous: bool = True,
    **kwargs
) -> Tensor

创建一个具有给定形状的张量,填充来自区间[0, 1)上均匀分布的随机值。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
t = Tensor.rand(2, 3)
print(t.numpy())
[[0.997  0.5899 0.2225]
 [0.7551 0.9057 0.8649]]
Source code in tinygrad/tensor.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
@staticmethod
def rand(*shape, device:str|None=None, dtype:DTypeLike|None=None, contiguous:bool=True, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[0, 1)`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  t = Tensor.rand(2, 3)
  print(t.numpy())
  ```
  """
  if not dtypes.is_float(dtype := to_dtype(dtype or dtypes.default_float)): raise ValueError(f"rand only supports float dtypes, got {dtype}")
  if not all_int(shape:=argfix(*shape)) or not all(s >= 0 for s in shape): raise ValueError(f"invalid input {shape=}")
  if device is not None and not isinstance(device, str): raise ValueError(f"rand only supports single device, got {device=}")
  device = Device.canonicalize(device)

  # if shape has 0, return zero tensor
  if (numel := prod(shape)) == 0: return Tensor.zeros(shape, device=device, dtype=dtype, **kwargs)
  num = ceildiv(numel * dtype.itemsize, 4)

  # generate per device seeds and rng counter if we haven't seen this device yet
  if device not in Tensor._device_seeds:
    Tensor._device_seeds[device] = Tensor(
      [int.from_bytes(hashlib.sha256(len(Tensor._device_seeds).to_bytes(4, "big")).digest(), "big"), Tensor._seed],
      device=device, dtype=dtypes.uint32, requires_grad=False)
    Tensor._device_rng_counters[device] = Tensor([0], device=device, dtype=dtypes.uint32, requires_grad=False)
  # increment rng counter for devices
  else: Tensor._device_rng_counters[device].assign(Tensor._device_rng_counters[device] + num).contiguous()

  # threefry random bits
  counts0 = (Tensor.arange(ceildiv(num, 2), device=device, dtype=dtypes.uint32, requires_grad=False)+Tensor._device_rng_counters[device])
  counts1 = counts0 + ceildiv(num, 2)
  bits = Tensor._threefry_random_bits(Tensor._device_seeds[device], counts0, counts1)[:num]

  # bitcast to uint with same number of bits
  _, nmant = dtypes.finfo(dtype)
  uint_dtype = {1: dtypes.uint8, 2: dtypes.uint16, 4: dtypes.uint32, 8: dtypes.uint64}[dtype.itemsize]
  bits = bits.bitcast(uint_dtype)
  # only randomize the mantissa bits and set the exponent to 1
  one = Tensor.ones_like(bits, device=bits.device, dtype=dtype).bitcast(uint_dtype)
  bits = bits.rshift((dtype.itemsize * 8) - nmant).bitwise_or(one)
  # bitcast back to the original dtype and reshape
  out = bits.bitcast(dtype)[:numel].sub(1).reshape(shape).requires_grad_(kwargs.get("requires_grad"))
  return out.contiguous() if contiguous else out

rand_like ¤

rand_like(**kwargs) -> Tensor

创建一个与self具有相同形状和分片的张量,其值填充为区间[0, 1)上均匀分布的随机值。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

t = Tensor.ones(2, 3)
print(Tensor.rand_like(t).numpy())
[[0.6213 0.9791 0.8408]
 [0.4178 0.6334 0.9325]]
Source code in tinygrad/tensor.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def rand_like(self, **kwargs) -> Tensor:
  """
  Creates a tensor with the same shape and sharding as `self`, filled with random values from a uniform distribution over the interval `[0, 1)`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  t = Tensor.ones(2, 3)
  print(Tensor.rand_like(t).numpy())
  ```
  """
  dtype = kwargs.pop("dtype", self.dtype)
  if isinstance(self.device, tuple):
    if kwargs.get("device") is not None: raise RuntimeError("cannot specify `device` on `rand_like` of a multi device tensor")
    if self.lazydata.axis is None: return Tensor.rand(*self.shape, dtype=dtype, **kwargs).shard(self.device)
    contiguous = kwargs.pop("contiguous", True)
    sharded_shape = tuple(s//len(self.device) if a==self.lazydata.axis else s for a,s in enumerate(self.shape))
    rands = [Tensor.rand(sharded_shape, device=d, dtype=dtype, contiguous=contiguous, **kwargs).lazydata for d in self.device]
    return Tensor(UOp.multi(*rands, axis=self.lazydata.axis), device=self.device, dtype=dtype, **kwargs)
  return Tensor.rand(*self.shape, device=kwargs.pop("device", self.device), dtype=dtype, **kwargs)

randn staticmethod ¤

randn(
    *shape,
    dtype: DTypeLike | None = None,
    requires_grad: bool | None = None,
    **kwargs
) -> Tensor

创建一个具有给定形状的张量,填充来自均值为0、标准差为1的正态分布的随机值。 如果未指定dtype,则使用默认类型。

你可以传入device关键字参数来控制张量的设备。 此外,所有其他关键字参数都会被传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.randn(2, 3).numpy())
[[ 0.9779  0.4678  0.5526]
 [-0.3288 -0.8555  0.2753]]
Source code in tinygrad/tensor.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
@staticmethod
def randn(*shape, dtype:DTypeLike|None=None, requires_grad:bool|None=None, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random values from a normal distribution with mean `0` and standard deviation `1`.
  If `dtype` is not specified, the default type is used.

  You can pass in the `device` keyword argument to control device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.randn(2, 3).numpy())
  ```
  """
  # https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
  src = Tensor.rand((2, *argfix(*shape)), **{**kwargs, "dtype": dtypes.float32})
  return (src[0].mul(2*math.pi).cos().mul((1 - src[1]).log().mul(-2).sqrt()).cast(dtype or dtypes.default_float)).requires_grad_(requires_grad)

randint staticmethod ¤

randint(
    *shape, low=0, high=10, dtype=int32, **kwargs
) -> Tensor

创建一个具有给定形状的张量,填充从区间[low, high)均匀生成的随机整数值。 如果未指定dtype,则使用默认类型。

你可以传入device关键字参数来控制张量的设备。 此外,所有其他关键字参数都会被传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.randint(2, 3, low=5, high=10).numpy())
[[9 7 6]
 [8 9 9]]
Source code in tinygrad/tensor.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
@staticmethod
def randint(*shape, low=0, high=10, dtype=dtypes.int32, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random integer values generated uniformly from the interval `[low, high)`.
  If `dtype` is not specified, the default type is used.

  You can pass in the `device` keyword argument to control device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.randint(2, 3, low=5, high=10).numpy())
  ```
  """
  if not isinstance(low, int) or not isinstance(high, int): raise TypeError(f"{low=} and {high=} must be integers")
  dtype = to_dtype(dtype)
  if not dtypes.is_int(dtype): raise TypeError(f"{dtype=} must be int")
  return Tensor.uniform(*shape, low=low, high=high, dtype=dtype, **kwargs)

普通 staticmethod ¤

normal(
    *shape,
    mean=0.0,
    std=1.0,
    requires_grad: bool | None = None,
    **kwargs
) -> Tensor

创建一个具有给定形状的张量,填充来自正态分布的随机值,该分布具有给定的mean均值和标准差std

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.normal(2, 3, mean=10, std=2).numpy())
[[11.9557 10.9356 11.1053]
 [ 9.3423  8.289  10.5505]]
Source code in tinygrad/tensor.py
758
759
760
761
762
763
764
765
766
767
768
769
770
771
@staticmethod
def normal(*shape, mean=0.0, std=1.0, requires_grad:bool|None=None, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random values from a normal distribution with the given `mean` and standard deviation `std`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.normal(2, 3, mean=10, std=2).numpy())
  ```
  """
  return ((std * Tensor.randn(*shape, **kwargs)) + mean).requires_grad_(requires_grad)

统一 staticmethod ¤

uniform(
    *shape,
    low=0.0,
    high=1.0,
    dtype: DTypeLike | None = None,
    requires_grad: bool | None = None,
    **kwargs
) -> Tensor

创建一个具有给定形状的张量,填充来自区间[low, high)上均匀分布的随机值。

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.uniform(2, 3, low=2, high=10).numpy())
[[9.9763 6.7193 3.7804]
 [8.0404 9.2452 8.9191]]
Source code in tinygrad/tensor.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
@staticmethod
def uniform(*shape, low=0.0, high=1.0, dtype:DTypeLike|None=None, requires_grad:bool|None=None, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random values from a uniform distribution over the interval `[low, high)`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.uniform(2, 3, low=2, high=10).numpy())
  ```
  """
  return (((high-low) * Tensor.rand(*shape, **kwargs)).cast(dtype or dtypes.default_float) + low).requires_grad_(requires_grad)

scaled_uniform staticmethod ¤

scaled_uniform(*shape, **kwargs) -> Tensor

创建一个具有给定形状的张量,填充来自均匀分布的随机值,区间为 [-prod(shape)**-0.5, prod(shape)**-0.5)

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.scaled_uniform(2, 3).numpy())
[[ 0.4058  0.0734 -0.2265]
 [ 0.2082  0.3312  0.2979]]
Source code in tinygrad/tensor.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
@staticmethod
def scaled_uniform(*shape, **kwargs) -> Tensor:
  """
  Creates a tensor with the given shape, filled with random values from a uniform distribution
  over the interval `[-prod(shape)**-0.5, prod(shape)**-0.5)`.

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.scaled_uniform(2, 3).numpy())
  ```
  """
  return Tensor.uniform(*shape, low=-1.0, high=1.0, **kwargs).mul(prod(argfix(*shape))**-0.5)

glorot_uniform staticmethod ¤

glorot_uniform(*shape, **kwargs) -> Tensor

https://www.tensorflow.org/api_docs/python/tf/keras/initializers/GlorotUniform

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.glorot_uniform(2, 3).numpy())
[[ 1.0889  0.197  -0.6079]
 [ 0.5588  0.8887  0.7994]]
Source code in tinygrad/tensor.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
@staticmethod
def glorot_uniform(*shape, **kwargs) -> Tensor:
  """
  <https://www.tensorflow.org/api_docs/python/tf/keras/initializers/GlorotUniform>

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.glorot_uniform(2, 3).numpy())
  ```
  """
  return Tensor.uniform(*shape, low=-1.0, high=1.0, **kwargs).mul((6/(argfix(*shape)[0]+prod(argfix(*shape)[1:])))**0.5)

kaiming_uniform staticmethod ¤

kaiming_uniform(
    *shape, a: float = 0.01, **kwargs
) -> Tensor

https://pytorch.org/docs/stable/_modules/torch/nn/init.html#kaiming_uniform_

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.kaiming_uniform(2, 3).numpy())
[[ 1.4058  0.2543 -0.7847]
 [ 0.7214  1.1473  1.032 ]]
Source code in tinygrad/tensor.py
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
@staticmethod
def kaiming_uniform(*shape, a:float = 0.01, **kwargs) -> Tensor:
  """
  <https://pytorch.org/docs/stable/_modules/torch/nn/init.html#kaiming_uniform_>

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.kaiming_uniform(2, 3).numpy())
  ```
  """
  bound = math.sqrt(3.0) * math.sqrt(2.0 / (1 + a ** 2)) / math.sqrt(prod(argfix(*shape)[1:]))
  return Tensor.uniform(*shape, low=-bound, high=bound, **kwargs)

kaiming_normal staticmethod ¤

kaiming_normal(*shape, a: float = 0.01, **kwargs) -> Tensor

https://pytorch.org/docs/stable/_modules/torch/nn/init.html#kaiming_normal_

你可以传入dtypedevice关键字参数来控制张量的数据类型和设备。 此外,所有其他关键字参数都会传递给张量的构造函数。

Tensor.manual_seed(42)
print(Tensor.kaiming_normal(2, 3).numpy())
[[ 0.7984  0.3819  0.4512]
 [-0.2685 -0.6985  0.2247]]
Source code in tinygrad/tensor.py
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@staticmethod
def kaiming_normal(*shape, a:float = 0.01, **kwargs) -> Tensor:
  """
  <https://pytorch.org/docs/stable/_modules/torch/nn/init.html#kaiming_normal_>

  You can pass in `dtype` and `device` keyword arguments to control the data type and device of the tensor.
  Additionally, all other keyword arguments are passed to the constructor of the tensor.

  ```python exec="true" source="above" session="tensor" result="python"
  Tensor.manual_seed(42)
  print(Tensor.kaiming_normal(2, 3).numpy())
  ```
  """
  std = math.sqrt(2.0 / (1 + a ** 2)) / math.sqrt(prod(argfix(*shape)[1:]))
  return Tensor.normal(*shape, mean=0.0, std=std, **kwargs)