In spring 618, the general Yuwen Huaji killed Emperor Yang in a coup and declared Emperor Yang's nephew Yang Hao the Prince of Qin emperor. While he killed a large number of high level officials and imperial Yang clan members, he did not kill Yang Gongren and made Yang Gongren the minister of civil service matters. After Yuwen advanced north of the elite Xiaoguo Army (驍果) but was defeated by Li Mi, he headed further north, and he left Yang Gongren defending Wei (魏縣, in modern Handan, Hebei). In 619, the Tang official Wei Zheng, however, persuaded another official Yuwen left at Wei, Yuan Baozang (元寶藏), to seize Yang Gongren and submit to Emperor Gaozu of Tang. Yuan delivered Yang Gongren to the Tang capital Chang'an. As Emperor Gaozu, while a Sui official, was a friend of Yang Gongren's, he released Yang Gongren and made him the assistant head of the examination bureau of the government (門下省, "Mengxia Sheng") and created him the Duke of Guan.