Skip to main content

Tensor

Struct Tensor 

Source
pub struct Tensor<T>
where T: Element,
{ /* private fields */ }
Expand description

テンソル本体。storage を複数の Tensor が共有することで view 系操作(transpose/narrow/reshape の contiguous ケース)を データコピーなしで表現する。

メモリレイアウト(行優先 + strides)は PoC-v2-1 の確定事項を 維持する。strides は stride 0 ブロードキャスト(broadcast_to/ broadcast_with。#12・TASK-1.4b)・将来の負 stride 拡張に備え isize とする(docs/public-api-design.md §2.1)。

Clone は Arc のポインタ複製のみで安価(データコピーを伴わない)。 PartialEq は意図的に derive しない: offset/strides が異なる 同値 view(例: 同一データを異なる narrow で参照した 2 つの Tensor)を構造的に不一致と誤判定するため。論理的な値の等価判定が 必要になった場合は要素比較の別 API として後続イシューで導入する。

Implementations§

Source§

impl Tensor<f32>

Source

pub fn cast<T>(&self) -> Result<Tensor<T>, ShapeError>
where T: CastElement,

self を Tensor<T> へ変換する(cast_from_f32 への薄い 委譲。イシュー #1750)。

T = f32 も許容するが、その場合は detached なコピーを返す だけであり(autodiff::Var::cast::<f32>() も同様に非微分・ detached)、勾配を保ったまま f32 系の恒等射を得たい場合は autodiff::Var::to_f32 を使うこと(本メソッドは値レベルの 変換のみを提供し、勾配伝播の意味論は autodiff 側の責務)。

Source§

impl<T> Tensor<T>
where T: CastElement,

Source

pub fn to_f32(&self) -> Result<Tensor<f32>, ShapeError>

self を Tensor<f32> へ変換する(cast_to_f32 への薄い 委譲。イシュー #1750)。T = f32 の場合は恒等コピー。

Source§

impl<T> Tensor<T>
where T: Element,

Source

pub fn new(data: Vec<T>, shape: &[usize]) -> Result<Tensor<T>, ShapeError>

実行時 shape 検査を行うコンストラクタ(PoC-v2-1 で確定した方式)。 data.len() が shape の要素数積と一致しない場合 ShapeError を 返す。要素数積のオーバーフローも生成前に検査する。

Source

pub fn from_slice(data: &[T], shape: &[usize]) -> Result<Tensor<T>, ShapeError>

data をコピーして new と同様に構築する。

Source

pub fn zeros(shape: &[usize]) -> Result<Tensor<T>, ShapeError>

全要素 T::zero() で埋めたテンソルを生成する。 shape の要素数積のオーバーフロー時に Err を返す (PoC の expect を排除し Result 化。本番経路で unwrap/ expect を使わない方針。.claude/rules/coding-rust.md)。

Source

pub fn ones(shape: &[usize]) -> Result<Tensor<T>, ShapeError>

全要素 T::one() で埋めたテンソルを生成する。

Source

pub fn full(shape: &[usize], value: T) -> Result<Tensor<T>, ShapeError>

全要素を value で埋めたテンソルを生成する。

Source

pub fn scalar(value: T) -> Tensor<T>

rank-0(スカラー)テンソルを構築する真に infallible なコンスト ラクタ(PR #403 codex-review P1 是正の一環で新設)。shape [] の 要素数積は空 iterator の乗法単位元 1 であり、checked_numel は 一度も checked_mul を呼ばずに Ok(1) を返す——すなわち Tensor::from_shape_fill と異なりオーバーフロー分岐が構造的に 存在しない。fandhe_ai_autodiff::eval::build_tensor・fandhe_ai_autodiff::tape の 各種安全側フォールバック(契約違反検知後にダミー値を返す経路)が、 from_shape_fill の Result を経由せず本番経路 panic 禁止規約を 満たすために使う。

Source

pub fn shape(&self) -> &[usize]

shape(各軸のサイズ)を返す。

Source

pub fn strides(&self) -> &[isize]

strides(各軸を 1 進めた際の要素インデックス増分)を返す。

Source

pub fn offset(&self) -> usize

storage 先頭からの要素オフセットを返す。

Source

pub fn rank(&self) -> usize

次元数(rank)を返す。

Source

pub fn numel(&self) -> usize

全要素数を返す。

Source

pub fn is_empty(&self) -> bool

要素数が 0 か判定する。

Source

pub fn get(&self, index: &[usize]) -> Option<T>

多次元インデックスから要素を取得する。

offset + Σ idx[i] * strides[i] で対象要素の位置を解決する (stride ベースアクセスの受け入れ条件検証に用いる基本 API)。 rank 不一致・軸範囲外は None を返す(型付きエラーではなく Option とするのは、ホットパスでの要素アクセスに Result の 分岐コストを強制しないため。範囲検査を伴う低頻度呼び出しの shape 検査は ShapeError を用いる view 系 API 側で行う)。

Source

pub fn as_slice(&self) -> Option<&[T]>

contiguous な場合のみ、storage 全体を指すスライスを返す。

後続のカーネル実装(backend-cpu 等、#21 以降)がデータへ 直接アクセスする際の受け渡し口として想定する。非 contiguous な テンソル(transpose/narrow 後)は連続領域を保証できないため None を返す。

numel() == 0(空テンソル)は is_contiguous() が常に true を 返す契約(上記コメント参照)に合わせ、ここでも無条件に Some(&[]) を返す。連続する narrow 呼び出しにより offset が storage 長を超えて押し出された空テンソルでは offset..offset(start == end だが start > storage.len())が storage.data.get で None になり得るため、要素 0 個の アクセスでは storage 範囲検査自体が無意味であることを踏まえ 早期 Some(&[]) で切り上げる(is_contiguous() == true ならば as_slice が必ず成功するという呼び出し元の前提を守るため)。

Source

pub fn host_slice(&self) -> Cow<'_, [T]>

ホスト可視の値を借用で読み出す(イシュー #1335)。

contiguous な場合は Self::as_slice の借用をそのまま Cow::Borrowed として返す(コピーなし)。非 contiguous な場合 (transpose/narrow 後の view)のみ Self::contiguous で 1 回だけ実体化し Cow::Owned として返す(Var::host_view/ facade 再エクスポートの内部実装が使う想定。docs/public-api- design.md §2.2 参照)。

Source

pub fn as_view_slice(&self) -> Option<&[T]>

非 contiguous な view でも、全 strides が非負である限り [offset, offset + span)(span = 1 + Σ (shape_i − 1)·stride_i)を storage から借用で返す(イシュー #1040)。

as_slice(contiguous 限定)と異なり、転置 view(transpose/ transpose2d 後の負でない stride を持つ view)もカバーする。 backend-metal::layout::classify_2d/collapse_leading_dims が 分類した view を、ホスト側で contiguous()(転置コピー)せずに そのまま GPU バッファへアップロードするための受け渡し口として 使う(呼び出し元がスライスの要素を layout 側の ld/transposed 契約で再解釈する前提。単純な「先頭から numel 個」の意味を持つ as_slice とは異なり、本メソッドが返すスライスはそれ自体では 論理形状を表さない)。

  • numel() == 0: Some(&[])(as_slice と同じ契約)
  • 負の stride を含む: None(Tensor の現行公開 API では transpose/narrow/broadcast_to のいずれも負 stride を 生成しないため到達しないが、将来の負 stride 拡張に備えた fail-safe)
  • span が storage 範囲を超える/offset + span がオーバー フローする: None
Source

pub fn transpose( &self, dim0: usize, dim1: usize, ) -> Result<Tensor<T>, ShapeError>

2 軸の strides を入れ替えるのみ。常に zero-copy。 転置後は非 contiguous になりうる(is_contiguous() で判定)。

Source

pub fn transpose_2d(&self) -> Result<Tensor<T>, ShapeError>

rank 2 テンソル専用の転置(transpose(0, 1) への薄い委譲)。

REQ-7(docs/spec/04-requirements.md)が明示する API 名。 safetensors 経由でロードした PyTorch nn.Linear.weight ([out_features, in_features])を matmul の右辺 ([in_features, out_features])へ変換する等、呼び出し側が 明示的に転置する用途を想定する(onnx-interop クレートの safetensors ローダーが暗黙アダプタを設けない方針の一部。 PoC-v2-6 mlp.rs の Mlp::from_safetensors と同型)。 rank ≠ 2 は ShapeError::RankMismatch を返す。

Source

pub fn permute(&self, perm: &[usize]) -> Result<Tensor<T>, ShapeError>

perm が指す軸順へ並べ替える N 階一般対応の転置(transpose の 2 軸限定を 補う。イシュー #274)。transpose と同じ zero-copy 方式(storage を Arc::clone で共有し、shape/strides の並べ替えのみを行う)。

perm[k] は出力軸 k が指す入力軸を表す(out_shape[k] == self.shape()[perm[k]]。 ONNX Transpose の perm 属性と同じ規約。onnx-interop::ops::shape_transform の呼び出し元がこの規約に依存する)。perm の長さが rank と一致しない場合は ShapeError::RankMismatch、範囲外の軸は ShapeError::AxisOutOfRange、重複軸は ShapeError::DuplicateAxis を返す(perm が 0..rank の順列であることを保証する)。

Source

pub fn narrow( &self, dim: usize, start: usize, len: usize, ) -> Result<Tensor<T>, ShapeError>

指定軸の [start, start+len) をスライスする。offset/shape の 調整のみで常に zero-copy。

Source

pub fn is_contiguous(&self) -> bool

現在のテンソルが行優先で連続配置されているか判定する。 サイズ 0・1 の軸は strides に依らず標準的に許容する (NumPy 等の慣習に合わせ、当該軸の stride 値は判定に用いない)。

numel() == 0(空テンソル)は常に連続とみなす(NumPy 方式)。 transpose/内側軸を長さ 0 まで narrow した後の空テンソルは 残った軸に非ゼロの stride を保持しうるが、row_major_strides は サイズ 0 の軸が存在すると外側の stride を 0 に潰す (row_major_strides の実装コメント参照)ため、要素アクセスが 発生しない空テンソルの軸ごと比較では偽陰性(誤って非連続と判定) になりうる。reshape/as_slice はいずれも本関数の結果を経由する ため、ここで早期 true を返すことで空テンソル同士の 有効な reshape・スライス取得を誤って弾かない。

Source

pub fn reshape(&self, shape: &[usize]) -> Result<Tensor<T>, ShapeError>

新しい shape へ再解釈する。contiguous な場合のみ zero-copy (storage を共有し新しい strides を割り当てるのみ)。

非 contiguous な場合は ShapeError::NonContiguousReshape を 返す(案 A。docs/public-api-design.md §2.2.1 が推奨する 安全側の方針。自動運転モードのため安全側に倒して採用した。 最終決定はユーザー承認事項として残っており、案 B(暗黙コピー) へ変更する場合はこの分岐のみを差し替えればよい)。

Source

pub fn contiguous(&self) -> Tensor<T>

非 contiguous な場合に、行優先連続バッファへ実体化した新しい Tensor を返す(常にコピーを伴う明示 API)。contiguous な場合は 自身の複製(Arc 共有のまま、コピーなし)を返す。

Source

pub fn broadcast_to(&self, shape: &[usize]) -> Result<Tensor<T>, ShapeError>

self を shape へブロードキャストした zero-copy view を返す (NumPy broadcast_to 相当。#12・TASK-1.4b)。

拡張された軸(元の軸長 1 が shape 側で 1 より大きい値に 広がる軸)は stride 0 の view になり、storage は Arc 共有の ままデータ複製を伴わない。縮小方向(例: [2,3] → [3])や 非互換 shape は ShapeError::BroadcastIncompatible を返す (lhs = 自身の shape・rhs = shape)。

アロケーション(Storage 複製)を伴わないため checked_numel のオーバーフロー検査は本来不要だが、後続の get/contiguous() 呼び出しで扱う要素数が usize 範囲を超えないことを構築時点で 保証するため、他の生成系 API と同様に事前検査する (.claude/rules/security.md A03 観点: fail-closed)。

Source

pub fn broadcast_with( &self, other: &Tensor<T>, ) -> Result<(Tensor<T>, Tensor<T>), ShapeError>

二項演算向け: self と other を共通の shape(NumPy 互換 ブロードキャスト規則で決定)へ揃えた view の組を返す (#12・TASK-1.4b)。backend-cpu の elementwise カーネル (#22)・autodiff の演算入口(#16〜#18)が二項演算前の shape 整合に用いる想定。

共通 shape の算出は broadcast_shape に委譲し、両者を broadcast_to で view 化する。いずれかが失敗した場合は ShapeError::BroadcastIncompatible を返す。

Trait Implementations§

Source§

impl<T> Clone for Tensor<T>
where T: Clone + Element,

Source§

fn clone(&self) -> Tensor<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> ConcatBatch for Tensor<T>
where T: Element,

Source§

fn concat_batches(parts: Vec<Tensor<T>>) -> Result<Tensor<T>, DataError>

parts を先頭軸で順に連結する。parts が空なら DataError::EmptyBatch。
Source§

impl<T> Debug for Tensor<T>
where T: Element,

Tensor<T> の手書き Debug 実装。

構造情報(shape/strides/offset/storage_len)を f.debug_struct で維持しつつ、data フィールドに打ち切り付きの 値プレビューを追加する。{:#?}(pretty-print)でも f.debug_struct 経由のため自然に整形される。shape/strides フィールドは SlicePreview 経由で出力し、data の打ち切りとは 独立に rank に依らず出力サイズを有界にする(P2 是正)。

Element: Debug は既存のトレイト境界(crate::element::Element) のみを使い、新規境界は追加しない(Element は unsealed 公開 trait のため必須メソッド追加は破壊的変更になる。既存の Debug 境界内で 完結させる設計判断は issue #1754 実装計画 §3.2 参照)。

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T> Display for Tensor<T>
where T: Element + Display,

Tensor<T> の Display 実装(Element: Display を持つ型限定)。

PyTorch の print(t) に寄せた tensor([[1, 2], [3, 4]]) 形式。 rank 0 は tensor(3)、空テンソル(いずれかの軸が 0)は値から shape を復元できないため tensor([], shape=[2, 0]) のように shape= を 付す。Element へ Display 境界は追加しない(impl 側の境界に 限定することでトレイト自体は非破壊のまま)。

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl PredictBatchInput for Tensor<f32>

Source§

fn inference_input(&self) -> &Tensor<f32>

推論入力の Tensor<f32> への参照(ラベルは含まない)。
Source§

impl<T> StackSamples for Tensor<T>
where T: Element,

Source§

type Batch = Tensor<T>

積み上げ後のバッチ型。
Source§

fn stack_samples( samples: Vec<Tensor<T>>, ) -> Result<<Tensor<T> as StackSamples>::Batch, DataError>

samples を先頭軸へ積む。空は DataError::EmptyBatch。

Auto Trait Implementations§

§

impl<T> Freeze for Tensor<T>
where Arc<Storage<T>>: Freeze,

§

impl<T> RefUnwindSafe for Tensor<T>
where Arc<Storage<T>>: RefUnwindSafe,

§

impl<T> Send for Tensor<T>
where Arc<Storage<T>>: Send,

§

impl<T> Sync for Tensor<T>
where Arc<Storage<T>>: Sync,

§

impl<T> Unpin for Tensor<T>
where Arc<Storage<T>>: Unpin,

§

impl<T> UnsafeUnpin for Tensor<T>
where Arc<Storage<T>>: UnsafeUnpin,

§

impl<T> UnwindSafe for Tensor<T>
where Arc<Storage<T>>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V