Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

try-using-ternary-dense #151

Open
david-thrower opened this issue Jun 11, 2024 · 0 comments
Open

try-using-ternary-dense #151

david-thrower opened this issue Jun 11, 2024 · 0 comments

Comments

@david-thrower
Copy link
Owner

Kind of issue: enhancement

Issue described: Try using a Ternary operation layer instead of a Dense layer, e.g. Replace each occurrence of tf.keras.layers.Dense with a custom layer like this:

import tensorflow as tf

class TernaryDenseLayer(tf.keras.layers.Layer):
    def __init__(self, units, input_dim, **kwargs):
        super(TernaryDenseLayer, self).__init__(**kwargs)
        self.units = units
        self.input_dim = input_dim
        self.ternary_weights = self.add_weight(name='ternary_weights', 
                                                shape=(input_dim, units),
                                                initializer='glorot_uniform',
                                                trainable=True)

    def build(self, input_shape):
        # Create a trainable weight variable for the bias
        self.bias = self.add_weight(name='bias', 
                                    shape=(self.units,),
                                    initializer='zeros',
                                    trainable=True)

    def call(self, inputs):
        # Apply ternary weights to the input vector
        ternary_inputs = tf.cast(tf.sign(inputs), tf.float32) * tf.abs(inputs)
        output = tf.matmul(ternary_inputs, self.ternary_weights)
        # Add bias and apply activation function
        output = tf.nn.bias_add(output, self.bias)
        output = tf.nn.relu(output)
        return output

Ultimately, it may be worth integrating this with what was done here: https://arxiv.org/pdf/2406.02528

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

When branches are created from issues, their pull requests are automatically linked.

1 participant