Background
HK was built as an assassin droid. He and the bounty hunter Zack Truss had a run-in when they were after the same target. Zack Truss's men managed to subdue and deactivate HK-51 and modify his internal programming to make him loyal to Zack.
Nearing the end of the great-hunt Zack Truss told his men that, if anything was to happen to him, they were to eliminate his challengers in the great hunt.
After seeing how resourceful Zoka and the rest of the team was, HK-51 decided it would be in his best interest to join the team instead of wiping them out.
Motivation
Quest: Rescue
Zack Truss has implanted HK with a chip that forces the droid to comply with his direct orders. Before Zack left on his final mission for the great hunt he gave HK an imperative that if Zack were to be captured, HK would be required to rescue him at any cost.