The 32-year-old American was due to face Petra Kvitova in the quarter-finals of the tournament but pulled out on Friday morning due to the problem.
Williams had worn a heavy strapping on her left leg in straight-sets victories over Belinda Bencic, Peng Shuai and Carla Suarez Navarro earlier in the week.
“I have an injury in my left thigh, and unfortunately I’ll have to retire from this year’s Mutua Madrid Open,” said Williams.
“I suffered it during my first-round match. I started to feel better but it is important that I have enough time to rest and recover.”
She said of her setback: “It’s very frustrating. This isn’t the way I wanted to end the week.”
Fifth seed Kvitova will now face either Simona Halep or Ana Ivanovic in the last four on Saturday.
MORE: The latest football news
MORE: The latest tennis news
BIOGRAPHY: Daniel Sturridge
BIOGRAPHY: Kepa Arrizabalaga