Tuesday, 23 January 2018

Higher level ops for building neural network layers with deeplearn.js

I have been meddling with google's deeplearn.js lately for fun. It is surprisingly good given how new the project is and it seems to have a sold roadmap. However it still lacks something like tf.layers and tf.contrib.layers which have many higher level functions that has made using tensorflow so easy. It looks like they will be added to Graphlayers in future but their priorities as of now is to fix the lower level APIs first - which totally makes sense.

So, I quickly built one for tf.layers.conv2d and tf.layers.flatten which I will share in this post. I have made them as close to function definitions in tensorflow as possible.

1.  conv2d - Functional interface for the 2D convolution layer.

  • inputs Tensor input.
  • filters Integer, the dimensionality of the output space (i.e. the number of filters in the convolution).
  • kernel_size Number to specify the height and width of the 2D convolution window.
  • graph Graph opbject.
  • strides Number to specify the strides of convolution.
  • padding One of "valid" or "same" (case-insensitive).
  • data_format "channels_last" or "channel_first"
  • activation Optional. Activation function which is applied on the final layer of the function. Function should accept Tensor and graph as parameters
  • kernel_initializer An initializer object for the convolution kernel.
  • bias_initializer  An initializer object for bias.
  • name string which represents name of the layer.

Tensor output.


Add this to your code:

2. flatten - Flattens an input tensor.

I wrote these snippets while building a tool using deeplearnjs where I do things like loading datasets, batching, saving checkpoints along with visualization. I will share more on that in my future posts.

Thursday, 11 January 2018

Hacking FaceNet using Adversarial examples

With the rise in popularity of face recognition systems with deep learning and it's application in security/ authentication, it is important to make sure that it is not that easy to fool them. I recently finished the 4th course on deeplearning.ai where there is an assignment which asks us to build a face recognition system - FaceNet. While I was working on the assignment, I couldn't stop thinking about how easy it is to fool it with adversarial examples. In this post I will tell you how I managed to do it.

First off, some basics about FaceNet. Unlike image recognition systems which map every image with a class, it is not possible to assign a class label to every face in face recognition. This is because one, there are way too many faces that a system should handle in the real world to assign class to each of them and two, if there are new people the system should handle, it can't do it. So, what we do is, we build a system that learns similarities and dissimilarities. Basically, there is a neural network similar to what we have in image recognition and instead of applying softmax in the end, we just take the logits as embedding for the given image input and then minimize something called the triplet loss.  Consider face A, we have a positive match P and negative match N. If f is the embedding function and L is the triplet loss, we have this:

Triplet loss

Basically, it is incentivizing small distance between A - P and large distance between A - N. Also, I really recommend watching Ian Goodfellow's lecture from Stanford's CS231n course if you want to know about adversarial examples.

Like I said earlier, this thought came to me while doing an assignment from 4th course from deeplearning.ai which can be found here and I have built on top of it.  The main idea here is to find small noise that when added to someone's photo although causing virtually no visual changes, can make faceNet identify them as the target.

Benoit (attacker)
Add noise
Kian Actual (Target)

First lets load the images of the attacker Benoit and the target Kian.

Now say that the attacker image is A` and the target image is T. We want to define triplet loss to achieve two things:

  1. Minimize distance between A` and T
  2. Maximize distance between A` and A` (original)
In other words the triplet loss L is:

L (A, P, N) = L (A`, T, A`)

Now, let's compute the gradient of the logits with respect to the input image 

These gradients are used to obtain the adversarial noise as follows :

noise = noise - step_size * gradients

According to the assignment, a l2 distance of the embeddings of less than 0.7 indicates that two faces have the same person. So lets do that.

The distance decreases from 0.862257 to 0.485102 which is considered enough in this case.

L2 distance between embeddings of attacker and target
This is impressive because, all this is done while not altering the image visibly just by adding a little calculated noise!

Also note that the l2 scores indicate that the generated image is more of Kian than Benoit in spite of looking practically identical to Benoit. So there you go, adversarial example generation for FaceNet.

Sunday, 17 December 2017

Tensorflow and AEM

It has been a while since google released Tensorflow support for java. Even though it is still in its infancy, I feel like it has everything we need. Build computation graphs - check, run session and compute stuff - check, GPU support - check. Now if you have all the time in the world to reinvent the wheel, you can pretty much build anything in java that we can build using python or c++.

So, I have been working on Adobe Experience Manager since I joined Adobe and recently, I started experimenting with several use cases where machine learning can help in content creation and discovery. As I have zero knowledge in building any deep learning models in java, I decided to build everything in java. How hard can it be? Right? Right? Sarcasm aside, as I mentioned earlier, Tensorflow for java has everything we need and as it internally uses JNI we can have interoperability with python and c++ (that's why I preferred this over deeplearning4j).

First off, I followed their official guide for the setup and had to face a lot of hurdles along the way. In this post I will show you how I managed to successfully setup Tensorflow on AEM (or any felix based systems).

Step 1

Add the dependency to your pom.xml file. Note that the scope set to compile.

Step 2

Add this configuration to your maven-bundle-plugin.

Step 3

Build and install to your AEM instance. Then, navigate to /system/console/bundles/ and look for the bundle which contains the dependency. See if the "Exported Packages" section has the following packages:

Step 4

Install JNI if necessary (this is mentioned in the link that I shared earlier).

Then place the library file in the appropriate place.


Lets write a simple sling servlet to check if everything is working as expected. Like I told earlier, Tensorflow for java is still in its infancy. So, I wrote a helper class a while back to manipulate the computation graph. Get GraphBuilder.java and place it where it is accessible to the sling servlet.


The following sling servlet includes things like:
  • Creating a computation graph
  • Creating placeholders, constants etc
  • Arithmetic operations, matrix multiplication.
  • Feeding data and computing values of placeholders.

When you go to /services/tftest you should get something like this:

4 -2 3 0 FLOAT tensor with shape [3, 3] 14 Testing done!
Now you can start building any deep learning model on AEM. Also, I will be writing about some of the real life applications of deep learning in content creation and content discovery. So stay tuned!

Wednesday, 29 March 2017

Most original prize at The 2017 Deep Learning Hackathon

Although I have worked on several deep learning projects in the past, I still consider myself to be a newbie in deep learning because of all the new things that keep coming up and it is so hard to keep up with all that. So, I decided to take part in "The 2017 Deep Learning Hackathon" by Deepgram to work on something I have been wanting to do for a while now.

I built something called Medivh - prophet from Warcraft who has seen the future.  The idea was to build a tool for web developers to predict how users are going to see / use the site even before deploying. Basically, it generates heat maps on websites which show where the user might look at. Example:

I will write another post with all the technical details. Here is the sneak peak of how it was done.

Apart from building that, We got an opportunity to interact with people like Bryan Catanzaro - maker of CUDNN and VP at Nvidia,  Jiaji Huangform from Baidu, Jonathan Hseu from Google Brain etc.

We also got to interact with people from Deepgram and their caffe like framework called Kur which seems pretty good. I think I'll write a review about Kur after playing around with it for some more time.

Also this:

This is me presenting before the results.
For Medivh, I won the "Most original prize" -  Nvidia Titan X pascal. What a beauty!

Thursday, 9 March 2017

Introducing mailing in crontab-ui

Now crontab-ui has option to send mails after execution of jobs along with output and errors attached as text files. This internally uses nodemailer and all the options available through nodemailer are available here.


To change the default transporter and mail config you can modify config/mailconfig.js.
var transporterStr = 'smtps://user%40gmail.com:password@smtp.gmail.com';

var mailOptions = {
    from: '"Fred Foo 👥" <foo@blurdybloop.com>', // sender address
    to: 'bar@blurdybloop.com, baz@blurdybloop.com', // list of receivers
    subject: 'Job Test#21 Executed ✔', // Subject line
    text: 'Test#21 results attached 🐴', // plaintext body
    html: '<b>Test#21 🐴</b> results attached' // html body


Make sure that you have node at /usr/local/bin/node else you need to create a softlink like this
ln -s [location of node] /usr/local/bin/node

Setting up crontab-ui on raspberry pi

In this tutorial I will show you how to setup crontab-ui on raspberry pi.

Step 1

Find your architecture
uname -a
Linux raspberrypi 4.4.50-v7+ #970 SMP Mon Feb 20 19:18:29 GMT 2017 armv7l GNU/Linux
Note that it is ARMv7. Download and extract latest node.
wget https://nodejs.org/dist/v7.7.2/node-v7.7.2-linux-armv7l.tar.xz
tar xz node-v7.7.2-linux-armv7l.tar.xz
sudo mv node-v7.7.2-linux-armv7l /opt/node

Step 2

Remove old nodejs if it is already installed and add the latest node to the $PATH
sudo apt-get purge nodejs
echo 'export PATH=$PATH:/opt/node/bin' > ~/.bashrc
source ~/.bashrc

Step 3

Install crontab-ui and pm2. And start crontab-ui.
npm install -g crontab-ui
npm install -g pm2
pm2 start crontab-ui
Now your crontab-ui must be running. Visit http://localhost:8000 on your browser to see if it is working.

Step 4 (Optional)

In order to be able access crontab-ui from outside, you have to forward the port 8000. Install nginx and configure.
sudo apt-get install nginx
sudo vi /etc/nginx/sites-available/default
Paste the following lines in the file:
server {
    listen 8001;

    server_name localhost;

    location / {
        proxy_pass http://localhost:8000;
Restart nginx
sudo service nginx restart
Now, crontab-ui must be accessible from outside through port 8001. So, to access crontab-ui, go to
<ip address of pi>:8001
You can also setup http authentication by following this.
Fork me on Github

Saturday, 28 January 2017

My solutions to cmdchallenge

I recently stumbled upon https://cmdchallenge.com which sort of tests your command line knowledge and comfortability. You have to basically solve all the challenges in a single line of bash. It is pretty simple and fun. You should give it a try before checking the solutions.


# Print "hello world".
# Hint: There are many ways to print text on
# the command line, one way is with the 'echo'
# command.
# Try it below and good luck!
echo "hello world"


# Print the current working directory.


# List all of the files in the current
# directory, one file per line.
ls -1


# Print the last 5 lines of "access.log".
tail -5 access.log


# There is a file named "access.log" in the
# current working directory. Print all lines
# in this file that contains the string "GET".
grep GET access.log


# Print all files, one per line that contain
# the string "500".
grep -rl * -e 500


# Print the relative file paths, one path
# per line for all files that start with
# "access.log" in the current directory.
find . -name "access.log*"


# Print all matching lines (without the filename
# or the file path) in all files under the current
# directory that start with "access.log" that
# contain the string "500".
find . -name "access.log*" | xargs grep -h 500


# Extract all IP addreses from files that
# that start with "access.log" printing one
# IP address per line.
find . -name "access.log*" | xargs grep -Eo '^[^ ]+'


# Delete all of the files in this challenge
# directory including all subdirectories and
# their contents.
find . -delete


# Count the number of files in the current
# working directory. Print the number of
# files as a single integer.
ls | wc -l


# Print the contents of access.log
# sorted.
sort access.log


# Print the number of lines
# in access.log that contain the string
# "GET".
grep GET access.log | wc -l


# The file split-me.txt contains a list of
# numbers separated by a ';' character.
# Split the numbers on the ';' character,
# one number per line.
cat split-me.txt | sed s/\;/\\n/g


# Print the numbers 1 to 100 separated
# by spaces.
echo {1..100}


# There are files in this challenge with
# different file extensions.
# Remove all files with the .doc extension
# recursively in the current working directory.
find . -name "*.doc" -delete


# This challenge has text files that contain
# the phrase "challenges are difficult". Delete
# this phrase recursively from all text files.
find . -name "*.txt" -exec sed -i 's/challenges are difficult//g' {} +


# The file sum-me.txt have a list of numbers,
# one per line. Print the sum of these numbers.
cat sum-me.txt | xargs | sed -e 's/\ /+/g' | bc


# Print all files in the current directory
# recursively without the leading directory path.
find . -type f -printf "%f\n"


# Remove the extension from all files in
# the current directory recursively.
Solution: (note you cant use find .)
find `pwd` -type f -exec bash -c 'mv "$1" "${1%.*}"' - '{}' \;


# The files in this challenge contain spaces.
# List all of the files in the current
# directory but replace all spaces with a '.'
# character.
find . -type f -printf "%f\n" | xargs -0 -I {} echo {} | tr ' ' '.'


# There are a mix of files in this directory
# that start with letters and numbers. Print
# the filenames (just the filenames) of all
# files that start with a number recursively
# in the current directory.
find . -name '[0-9]*' -type f -printf "%f\n"


# Print the 25th line of the file faces.txt
sed '25q;d' faces.txt


# Print the file faces.txt, but only print the first instance of each
# duplicate line, even if the duplicates don't appear next to each other.
awk '!seen[$0]++' faces.txt


# You have a new challenge!
# The following excerpt from War and Peace is saved to
# the file 'war_and_peace.txt':
# She is betraying us! Russia alone must save Europe.
# Our gracious sovereign recognizes his high vocation
# and will be true to it. That is the one thing I have
# faith in! Our good and wonderful sovereign has to
# perform the noblest role on earth, and he is so virtuous
# and noble that God will not forsake him. He will fulfill
# his vocation and crush the hydra of revolution, which
# has become more terrible than ever in the person of this
# murderer and villain!
# The file however has been corrupted, there are random '!'
# marks inserted throughout.  Print the original text.
Solution: (Found this on hackernews)
< war_and_peace.txt tr -s '!' | sed 's/!\([a-z]\)/\1/g' | sed 's/!\( [a-z]\)/\1/g' | sed 's/!\.!/./g' | sed 's/ !/ /g'

Also, you can checkout the creator's solutions here.

Thursday, 19 January 2017

Look before you paste from a website to terminal

Most of the time when we see a code snippet online to do something, we often blindly copy paste it to the terminal. Even the tech savy ones just see it on the website before copy pasting. Here is why you shouldn't do this. Try pasting the following line to your terminal (SFW)

ls ; clear; echo 'Haha! You gave me access to your computer with sudo!'; echo -ne 'h4cking ## (10%)\r'; sleep 0.3; echo -ne 'h4cking ### (20%)\r'; sleep 0.3; echo -ne 'h4cking ##### (33%)\r'; sleep 0.3; echo -ne 'h4cking ####### (40%)\r'; sleep 0.3; echo -ne 'h4cking ########## (50%)\r'; sleep 0.3; echo -ne 'h4cking ############# (66%)\r'; sleep 0.3; echo -ne 'h4cking ##################### (99%)\r'; sleep 0.3; echo -ne 'h4cking ####################### (100%)\r'; echo -ne '\n'; echo 'Hacking complete.'; echo 'Use GUI interface using visual basic to track my IP'

It should look something like this once it is pasted onto your terminal.
View post on imgur.com
You probably guessed it. There is some malicious code between ls and -lat that is hidden from the user

Malicious code's color is set to that of the background, it's font size is set to 0, it is moved away from rest of the code and it is made un-selectable (that blue color thing doesn't reveal it); to make sure that it works in all possible OSes, browsers and screen sizes.

This can be worse. If the code snippet had a command with sudo for instance, the malicious code will have sudo access too. Or, it can silently install a keylogger on your machine; possibilities are endless. So, the lesson here is, make sure that you paste code snippets from untrusted sources onto a text editor before executing it.

Thanks for reading!

Tuesday, 18 October 2016

How to download large folders on dropbox

Recently, someone shared a large folder with me and when I tried to download it, I was getting an error; "There was an error downloading your file".
This error seemed very vague and after a quick search online, I figured out that it is not possible to download folders which are bigger than 1 GB.  And according to dropbox's help article, I will be able to download it only if I add it to my dropbox. With dropbox's puny 2GB free storage it was not possible and I was not ready to spend $$$ just for this. 
So, I wrote a simple script in javascript that I can run it on browser console to download all files in a folder!

How to do it?

Step 1. Navigate to the dropbox folder on the browser and open your developer console. Press   cmd + j  on mac or  ctrl + shift + j  on linux and windows.

Step 2. Paste the following code in the console.

Step 3. The browser will try to block the windows trying to download it. Select the option to  Always allow pop-ups from https://www.dropbox.com . For instance this is how it will look on Google Chrome (you have to click on right most icon in the search bar).

Step 4. Your files will be downloaded one by one!

NOTE: If any folder inside the folder is greater than 1GB in size, then you may have to do the same process after navigating to that folder in the browser.

Update: Make sure that you use the list view to see files by clicking on this:

Thursday, 15 September 2016

Right way to set env variable while exec or execFile in nodejs

According to the official documentation, exec allows you to pass additional environment variables as part of options like this:

This looks fine right? except that it totally isn't! By passing "env" as an option, you are not adding on to existing environment variables, but you are replacing it.  This is not clear from the documentation and can leave you scratching your head for a while as it can seem to break the command for no particular reason at all! So, you need to essentially make a copy of process.env and modify it like follows.

Thanks for stopping by!