Skip to main content

prediction with tensorflow model being much slower than on tensorflow.js with a default configuration on a macbook M1

I'm likely doing something very wrong. Since the prediction was much slower on python I've written two, seemingly equivalent, snippets to test the two libraries.

In Python (Python 3.9.12):

from tensorflow.python.keras.layers import Dense, Flatten
from tensorflow.python.keras.models import Sequential
import time
from tensorflow.python.client import device_lib


def create_model():
    input_shape = (1, 300)
    model = Sequential()
    model.add(Dense(200, activation="elu", input_shape=input_shape))
    model.add(Flatten())
    model.add(Dense(50, activation="elu"))
    model.add(Dense(20, activation="linear"))
    model.compile()
    return model


if __name__ == '__main__':
    print(device_lib.list_local_devices())
    model = create_model()
    inp = [[[0.5] * 300]]

    # warmup
    for i in range(0, 100):
        model.predict(inp)

    start_time = time.time()
    for i in range(0, 100):
        model.predict(inp)

    end_time = time.time()
    print(f" {end_time - start_time} s")

In JS (running on node v19.6.1):

import * as tf from "@tensorflow/tfjs-node";


function createModel(): tf.LayersModel {
    const model = tf.sequential();
    const inputShape = [1, 300]
    model.add(tf.layers.dense({activation: "elu", units: 200, inputShape: inputShape}));
    model.add(tf.layers.flatten())
    model.add(tf.layers.dense({activation: "elu", units: 50}));
    model.add(tf.layers.dense({activation: "linear", units: 20}));
    return model
}


const be = tf.getBackend()
console.log(be)
const model = createModel()
const inp = tf.tensor([[new Array(300).fill(0.5)]])
//warmup
for (let i = 0; i < 100; i++) {
    model.predict(inp)
}

console.time("p time");
for (let i = 0; i < 100; i++) {
    model.predict(inp)
}
console.timeEnd("p time")

The relative output for python:

python benchmark.py

[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 11057909948552266533
xla_global_id: -1
]
2023-03-26 21:54:03.426043: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
 3.1207358837127686 s

and node:

> ts-node  src/benchmark.ts

tensorflow
p time: 32.62ms

These are the specs of the mac:

Hardware Overview:

  Model Name:   MacBook Pro
  Model Identifier: MacBookPro18,1
  Chip: Apple M1 Pro
  Total Number of Cores:    10 (8 performance and 2 efficiency)
  Memory:   16 GB
  System Firmware Version:  7429.61.2
  OS Loader Version:    7429.61.2
  Serial Number (system):   WGR2WKVPX6
  Hardware UUID:    743BE62E-85CA-5B60-BA83-2F4EB16926CB
  Provisioning UDID:    00006000-0014690E22A1801E
  Activation Lock Status:   Disabled

I could understand a small difference but not a gap of 100 times. Any pointers?

I would have expected the execution to take a comparable amount of time with both libraries or tensorflow being faster.



source https://stackoverflow.com/questions/75850282/prediction-with-tensorflow-model-being-much-slower-than-on-tensorflow-js-with-a

Comments

Popular posts from this blog

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...