kndrtt
kndrtt

Reputation: 13

How to correctly write @vectorize decorator's signatures with numba

I want to add a decorator to the function which requires 7 arguments such as:

  1. n = 1000000

  2. greyscales = np.floor(np.random.uniform(0, 255, n).astype(np.float32))

  3. weights = np.random.normal(.5, .1, n).astype(np.float32)

  4. exp

  5. @vectorize('float32(float32)', target = 'cuda')
    def normalize(greyscales):
        return greyscales / 255
    
  6. @vectorize('float32(float32,float32)', target = 'cuda')
    def weigh(values, weights):
        return values * weights
    
  7. @vectorize('float32(float32)', target = 'cuda')        
    def activate(values):
        a = exp(values)
        b = exp(-values)
        return (a - b) / (a + b)
    

And the function itself looks like this:

@vectorize('float32(int,float32,float32,float32,float32,float32,float32)', target='cuda')
def create_hidden_layer(n, greyscales, weights, exp, normalize, weigh, activate):
    normalized = normalize(greyscales)
    weighted = weigh(normalized, weights)
    activated = activate(weighted)
    return activated

I got stuck with choosing signatures for @vectorize, especially don't know how to define n and exp. Maybe someone could help me?

Upvotes: 0

Views: 230

Answers (1)

Rafnus
Rafnus

Reputation: 312

As Rutger Kassies has also said, there does not seem to be a good reason why the create_hidden_layer function has to take the other functions as an input. So you can simply remove that part to make it work,also you should note a couple of other things:

  • numba can infer which types a function accepts/outputs, so specifying them is not mandatory.
  • "EXP" whatever that means, just use the numpy library exp function, which already has very good performance.

This version of the code should work: (I have removed the cuda part to make it work on my machine):

import numpy as np
from numba import vectorize

n = 1000000
greyscales = np.floor(np.random.uniform(0, 255, n).astype(np.float32))
weights = np.random.normal(.5, .1, n).astype(np.float32)

@vectorize('float32(float32)')
def normalize(greyscales):
    return greyscales / 255
@vectorize('float32(float32,float32)')
def weigh(values, weights):
    return values * weights
@vectorize('float32(float32)')        
def activate(values):
    a = np.exp(values)
    b = np.exp(-values)
    return (a - b) / (a + b)

@vectorize()
    def create_hidden_layer(n, greyscales, weights):
        normalized = normalize(greyscales)
        weighted = weigh(normalized, weights)
        activated = activate(weighted)
        return activated
    
create_hidden_layer(n, greyscales, weights)

Upvotes: 1

Related Questions