license import { ENGINE } from '../engine' ; import { Tile , TileAttrs , TileInputs } from '../kernel_names' ; import { NamedAttrMap } from '../kernel_registry' ; import { Tensor } from '../tensor' ; import { NamedTensorMap } from '../tensor_types' ; import { convertToTensor } from '../tensor_util_env' ; import { Rank , ShapeMap , TensorLike } from '../types' ; import { clone } from './clone' ; import { op } from './operation' ; import { reshape } from './reshape' ; param input param shape doc function broadcastTo_ < R extends Rank > ( x , shape ) { let input = convertToTensor ( x , 'broadcastTo' , 'x' ) ; const xShape = input . shape ; if ( shape . some ( d => ! ( d > 0 ) || d % 1 !== 0 ) ) { throw new Error ( `broadcastTo(): Invalid broadcast shape [${ shape }].` ) ; } if ( shape . length < input . rank ) { throw new Error ( `broadcastTo(): shape.length=${ shape . length } < input.rank=${ input . rank }.` ) ; } if ( shape . length > input . rank ) { const newShape = input . shape . slice ( ) ; while ( newShape . length < shape . length ) { newShape . unshift ( 1 ) ; } input = reshape ( input , newShape ) ; } const inputShape = input . shape ; const reps = Array . from ( shape ) ; for ( let i = shape . length - 1 ; i >= 0 ; i -- ) { if ( inputShape [ i ] === shape [ i ] ) { reps [ i ] = 1 ; } else if ( input . shape [ i ] !== 1 ) { throw new Error ( `broadcastTo(): [${ xShape }] cannot be broadcast to [${ shape }].` ) ; } } const axes = reps . map ( ( n , i ) => n > 1 ? i : - 1 ) . filter ( i => i >= 0 ) ; if ( axes . length === 0 ) { return clone ( input ) as Tensor < R > ; } const inputs = { x : input } ; const attrs = { reps } ; return ENGINE . runKernel ( Tile , inputs as { } as NamedTensorMap , attrs as unknown as NamedAttrMap ) ; } export const broadcastTo = op ( { broadcastTo_ } ) ;