<commit_before>package be.iminds.iot.dianne.nn.module.activation;

import java.util.UUID;

import be.iminds.iot.dianne.nn.module.AbstractModule;
import be.iminds.iot.dianne.tensor.TensorFactory;

public class Softmax extends AbstractModule {

	public Softmax(TensorFactory factory) {
		super(factory);
	}
	
	public Softmax(TensorFactory factory, UUID id) {
		super(factory, id);
	}
	
	@Override
	protected void forward() {
		output = factory.getTensorMath().softmax(output, input);
	}

	@Override
	protected void backward() {
		float sum = factory.getTensorMath().sum(factory.getTensorMath().cmul(null, gradOutput, output));
		
		gradInput = factory.getTensorMath().sub(gradInput, gradOutput, sum);
		gradInput = factory.getTensorMath().cmul(gradInput, output, gradInput);
	}
}<commit_msg>add small term in softmax to avoid resulting to zeros and a one<commit_after>package be.iminds.iot.dianne.nn.module.activation;

import java.util.UUID;

import be.iminds.iot.dianne.nn.module.AbstractModule;
import be.iminds.iot.dianne.tensor.TensorFactory;

public class Softmax extends AbstractModule {

	private float alpha = 0.0001f;
	
	public Softmax(TensorFactory factory) {
		super(factory);
	}
	
	public Softmax(TensorFactory factory, UUID id) {
		super(factory, id);
	}
	
	@Override
	protected void forward() {
		output = factory.getTensorMath().softmax(output, input);
		
		// this makes sure that you don't end up with zeros and a one, which 
		// gives -Inf in the NLL ... this does add a (small) error though...
		output = factory.getTensorMath().add(output, output, alpha);
		output = factory.getTensorMath().div(output, output, 1f + alpha*output.size());
	}

	@Override
	protected void backward() {
		float sum = factory.getTensorMath().sum(factory.getTensorMath().cmul(null, gradOutput, output));
		
		gradInput = factory.getTensorMath().sub(gradInput, gradOutput, sum);
		gradInput = factory.getTensorMath().cmul(gradInput, output, gradInput);
	}
}
{'fraction_non_alphanumeric': 0.12339989759344598, 'fraction_numerical': 0.0030721966205837174, 'mean_word_length': 4.76401179941003, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3754599', 'n_tokens_mistral': 662, 'n_tokens_neox': 612, 'n_words': 147}