Skip to content

Commit

Permalink
Fix missing isTypedArray when mixing versions of @tensorflow packages
Browse files Browse the repository at this point in the history
A new function, `isTypedArray` was added to the `platform` interface by tensorflow#7181
and first published in tfjs-core 4.2.0. This made 4.2.0 incompatible with
earlier versions of backends that implemented `platform`, such as node and
react-native. This change adds a fallback to the use of `isTypedArray` so
earlier versions of platforms that don't implement `isTypedArray` will not throw
an error.

Note that the fallback behavior may not be perfect, such as when running Jest
tests in node. See tensorflow#7175 for more details and upgrade all @tensorflow scoped
packages to ^4.2.0 to avoid this.

Fixes tensorflow#7273
  • Loading branch information
mattsoulanille committed Mar 16, 2023
1 parent e1fd1f1 commit fb95890
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 7 additions & 2 deletions tfjs-core/src/platforms/platform_browser.ts
Expand Up @@ -93,11 +93,16 @@ export class PlatformBrowser implements Platform {

isTypedArray(a: unknown): a is Uint8Array | Float32Array | Int32Array
| Uint8ClampedArray {
return a instanceof Float32Array || a instanceof Int32Array ||
a instanceof Uint8Array || a instanceof Uint8ClampedArray;
return isTypedArrayBrowser(a);
}
}

export function isTypedArrayBrowser(a: unknown): a is Uint8Array
| Float32Array | Int32Array | Uint8ClampedArray {
return a instanceof Float32Array || a instanceof Int32Array ||
a instanceof Uint8Array || a instanceof Uint8ClampedArray;
}

if (env().get('IS_BROWSER')) {
env().setPlatform('browser', new PlatformBrowser());

Expand Down
4 changes: 3 additions & 1 deletion tfjs-core/src/util.ts
Expand Up @@ -16,6 +16,7 @@
*/

import {env} from './environment';
import { isTypedArrayBrowser, PlatformBrowser } from './platforms/platform_browser';
import {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';
import * as base from './util_base';
export * from './util_base';
Expand Down Expand Up @@ -134,7 +135,8 @@ export function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {

export function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|
Uint8ClampedArray {
return env().platform.isTypedArray(a);
const isTypedArray = env().platform.isTypedArray || isTypedArrayBrowser;
return isTypedArray(a);
}

// NOTE: We explicitly type out what T extends instead of any so that
Expand Down

0 comments on commit fb95890

Please sign in to comment.